当前位置: 首页>>代码示例>>Python>>正文


Python typing._ForwardRef方法代码示例

本文整理汇总了Python中typing._ForwardRef方法的典型用法代码示例。如果您正苦于以下问题:Python typing._ForwardRef方法的具体用法?Python typing._ForwardRef怎么用?Python typing._ForwardRef使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在typing的用法示例。


在下文中一共展示了typing._ForwardRef方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: resolve_annotations

# 需要导入模块: import typing [as 别名]
# 或者: from typing import _ForwardRef [as 别名]
def resolve_annotations(raw_annotations: Dict[str, Type[Any]], module_name: Optional[str]) -> Dict[str, Type[Any]]:
    """
    Partially taken from typing.get_type_hints.

    Resolve string or ForwardRef annotations into type objects if possible.
    """
    if module_name:
        base_globals: Optional[Dict[str, Any]] = sys.modules[module_name].__dict__
    else:
        base_globals = None
    annotations = {}
    for name, value in raw_annotations.items():
        if isinstance(value, str):
            if sys.version_info >= (3, 7):
                value = ForwardRef(value, is_argument=False)
            else:
                value = ForwardRef(value)
        try:
            value = _eval_type(value, base_globals, None)
        except NameError:
            # this is ok, it can be fixed with update_forward_refs
            pass
        annotations[name] = value
    return annotations 
开发者ID:samuelcolvin,项目名称:pydantic,代码行数:26,代码来源:typing.py

示例2: test_forwardref_instance_type_error

# 需要导入模块: import typing [as 别名]
# 或者: from typing import _ForwardRef [as 别名]
def test_forwardref_instance_type_error(self):
        fr = typing._ForwardRef('int')
        with self.assertRaises(TypeError):
            isinstance(42, fr) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:6,代码来源:test_typing.py

示例3: test_forwardref_subclass_type_error

# 需要导入模块: import typing [as 别名]
# 或者: from typing import _ForwardRef [as 别名]
def test_forwardref_subclass_type_error(self):
        fr = typing._ForwardRef('int')
        with self.assertRaises(TypeError):
            issubclass(int, fr) 
开发者ID:ShikyoKira,项目名称:Project-New-Reign---Nemesis-Main,代码行数:6,代码来源:test_typing.py

示例4: test_forward_equality

# 需要导入模块: import typing [as 别名]
# 或者: from typing import _ForwardRef [as 别名]
def test_forward_equality(self):
        fr = typing._ForwardRef('int')
        self.assertEqual(fr, typing._ForwardRef('int'))
        self.assertNotEqual(List['int'], List[int]) 
开发者ID:ShikyoKira,项目名称:Project-New-Reign---Nemesis-Main,代码行数:6,代码来源:test_typing.py

示例5: test_forward_repr

# 需要导入模块: import typing [as 别名]
# 或者: from typing import _ForwardRef [as 别名]
def test_forward_repr(self):
        self.assertEqual(repr(List['int']), "typing.List[_ForwardRef('int')]") 
开发者ID:ShikyoKira,项目名称:Project-New-Reign---Nemesis-Main,代码行数:4,代码来源:test_typing.py

示例6: get_forward_ref_type

# 需要导入模块: import typing [as 别名]
# 或者: from typing import _ForwardRef [as 别名]
def get_forward_ref_type() -> Any:
    # ignoring mypy on the import as it catches (_)ForwardRef as invalid, use for
    # introspection is valid:
    # https://docs.python.org/3/library/typing.html#typing.ForwardRef
    if "ForwardRef" in dir(typing):
        return typing.ForwardRef  # type: ignore
    return typing._ForwardRef  # type: ignore 
开发者ID:aws-cloudformation,项目名称:cloudformation-cli-python-plugin,代码行数:9,代码来源:recast.py

示例7: ensure_forward_ref

# 需要导入模块: import typing [as 别名]
# 或者: from typing import _ForwardRef [as 别名]
def ensure_forward_ref(self, service, factory, instance, **kwargs):
    if isinstance(service, str):
        self.register(ForwardRef(service), factory, instance, **kwargs) 
开发者ID:bobthemighty,项目名称:punq,代码行数:5,代码来源:_compat.py

示例8: evaluate_forwardref

# 需要导入模块: import typing [as 别名]
# 或者: from typing import _ForwardRef [as 别名]
def evaluate_forwardref(type_: ForwardRef, globalns: Any, localns: Any) -> Any:
        return type_._eval_type(globalns, localns) 
开发者ID:samuelcolvin,项目名称:pydantic,代码行数:4,代码来源:typing.py

示例9: update_field_forward_refs

# 需要导入模块: import typing [as 别名]
# 或者: from typing import _ForwardRef [as 别名]
def update_field_forward_refs(field: 'ModelField', globalns: Any, localns: Any) -> None:
    """
    Try to update ForwardRefs on fields based on this ModelField, globalns and localns.
    """
    if field.type_.__class__ == ForwardRef:
        field.type_ = evaluate_forwardref(field.type_, globalns, localns or None)
        field.prepare()
    if field.sub_fields:
        for sub_f in field.sub_fields:
            update_field_forward_refs(sub_f, globalns=globalns, localns=localns) 
开发者ID:samuelcolvin,项目名称:pydantic,代码行数:12,代码来源:typing.py

示例10: resolve_fw_decl

# 需要导入模块: import typing [as 别名]
# 或者: from typing import _ForwardRef [as 别名]
def resolve_fw_decl(in_type, module_name=None, globs=None, level=0,
        search_stack_depth=2):
    '''Resolves forward references in ``in_type``, see
    https://www.python.org/dev/peps/pep-0484/#forward-references.


    Note:

    ``globs`` should be a dictionary containing values for the names
    that must be resolved in ``in_type``. If ``globs`` is not provided, it
    will be created by ``__globals__`` from the module named ``module_name``,
    plus ``__locals__`` from the last ``search_stack_depth`` stack frames (Default: 2),
    beginning at the calling function. This is to resolve cases where ``in_type`` and/or
    types it fw-references are defined inside a function.

    To prevent walking the stack, set ``search_stack_depth=0``.
    Ideally provide a proper ``globs`` for best efficiency.
    See ``util.get_function_perspective_globals`` for obtaining a ``globs`` that can be
    cached. ``util.get_function_perspective_globals`` works like described above.
    '''
    # Also see discussion at https://github.com/Stewori/pytypes/pull/43
    if in_type in _fw_resolve_cache:
        return _fw_resolve_cache[in_type], True
    if globs is None:
        #if not module_name is None:
        globs = util.get_function_perspective_globals(module_name, level+1,
                level+1+search_stack_depth)
    if isinstance(in_type, _basestring):
        # For the case that a pure forward ref is given as string
        out_type = eval(in_type, globs)
        _fw_resolve_cache[in_type] = out_type
        return out_type, True
    elif isinstance(in_type, ForwardRef):
        # Todo: Mabe somehow get globs from in_type.__forward_code__
        if not in_type.__forward_evaluated__:
            in_type.__forward_value__ = eval(in_type.__forward_arg__, globs)
            in_type.__forward_evaluated__ = True
            return in_type, True
    elif is_Tuple(in_type):
        return in_type, any([resolve_fw_decl(in_tp, None, globs)[1] \
                for in_tp in get_Tuple_params(in_type)])
    elif is_Union(in_type):
        return in_type, any([resolve_fw_decl(in_tp, None, globs)[1] \
                for in_tp in get_Union_params(in_type)])
    elif is_Callable(in_type):
        args, res = get_Callable_args_res(in_type)
        ret = any([resolve_fw_decl(in_tp, None, globs)[1] \
                for in_tp in args])
        ret = resolve_fw_decl(res, None, globs)[1] or ret
        return in_type, ret
    elif hasattr(in_type, '__args__') and in_type.__args__ is not None:
        return in_type, any([resolve_fw_decl(in_tp, None, globs)[1] \
                for in_tp in in_type.__args__])
    return in_type, False 
开发者ID:Stewori,项目名称:pytypes,代码行数:56,代码来源:type_util.py


注:本文中的typing._ForwardRef方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。