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


Python typing.ForwardRef方法代码示例

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


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

示例1: lookup_method

# 需要导入模块: import typing [as 别名]
# 或者: from typing import ForwardRef [as 别名]
def lookup_method(self, operator, *args, node):
        """Helper method to lookup a method type given the operator and types of arguments.

        TODO: modify this implementation to use mro.
        """
        if args:
            # First try to do a direct lookup.
            if isinstance(args[0], ForwardRef) and operator in self.classes[args[0].__forward_arg__]:
                for func_type, _ in self.classes[args[0].__forward_arg__][operator]:
                    if len(args) != len(func_type.__args__) - 1:
                        continue
                    if self.type_constraints.can_unify(Callable[list(args), Any],
                                                       Callable[list(func_type.__args__[:-1]), Any]):
                        return func_type

            # If that doesn't work, fall back on a brute force search.
            func_types_list = self.methods[operator]
            for func_type, _ in func_types_list:
                if len(args) != len(func_type.__args__) - 1:
                    continue
                if self.type_constraints.can_unify(Callable[list(args), Any],
                                                   Callable[list(func_type.__args__[:-1]), Any]):
                    return func_type
            return TypeFailFunction(tuple(func_types_list), None, node) 
开发者ID:pyta-uoft,项目名称:pyta,代码行数:26,代码来源:type_store.py

示例2: literal_substitute

# 需要导入模块: import typing [as 别名]
# 或者: from typing import ForwardRef [as 别名]
def literal_substitute(t: type, type_map: Dict[str, type]) -> type:
    """Make substitutions in t according to type_map, returning resulting type."""
    if isinstance(t, TypeVar) and t.__name__ in type_map:
        return type_map[t.__name__]
    elif isinstance(t, TypeVar):
        return TypeVar(t.__name__)
    elif isinstance(t, ForwardRef):
        return ForwardRef(literal_substitute(t.__forward_arg__, type_map))
    elif isinstance(t, TuplePlus):
        subbed_args = [literal_substitute(t1, type_map) for t1 in t.__constraints__]
        return TuplePlus('tup+', *subbed_args)
    elif is_callable(t):
        args = list(literal_substitute(t1, type_map) for t1 in t.__args__[:-1])
        res = literal_substitute(t.__args__[-1], type_map)
        new_t = Callable[args, res]
        if hasattr(t, '__polymorphic_tvars__'):
            new_t.__polymorphic_tvars__ = t.__polymorphic_tvars__.copy()
        return new_t
    elif isinstance(t, _GenericAlias) and t.__args__ is not None:
        return t.copy_with(tuple(literal_substitute(t1, type_map) for t1 in t.__args__))
    else:
        return t 
开发者ID:pyta-uoft,项目名称:pyta,代码行数:24,代码来源:base.py

示例3: _type_str

# 需要导入模块: import typing [as 别名]
# 或者: from typing import ForwardRef [as 别名]
def _type_str(type):
    if isinstance(type, TypeVar) or isinstance(type, _GenericAlias) or \
            type.__class__.__name__ == '_Any' or \
            isinstance(type, ForwardRef) or type is None:
        return str(type).replace('typing.', '')
    elif getattr(type, '__origin__', None) is Union:
        trimmed_args = []
        for arg in type.__args__:
            if not isinstance(arg, _GenericAlias):
                trimmed_args.append(_type_str(arg))
            else:
                break
        if len(trimmed_args) == 0:
            trimmed_args.append(_type_str(type.__args__[0]))
        if len(trimmed_args) != len(type.__args__):
            trimmed_args.append('...')
        return 'Union[%s]' % ', '.join(trimmed_args)
    else:
        return type.__name__ 
开发者ID:pyta-uoft,项目名称:pyta,代码行数:21,代码来源:draw_tnodes.py

示例4: _validate_list_types

# 需要导入模块: import typing [as 别名]
# 或者: from typing import ForwardRef [as 别名]
def _validate_list_types(self, actual_value, expected_type):
        """
        Recursively checks nested lists like List[List[str]] and checks that
        all elements in the list are uniform
        """
        # typing.List[type] will have __args__
        if isinstance(actual_value, list) and \
           hasattr(expected_type, '__args__'):
            nested_type = expected_type.__args__[0]
            if isinstance(nested_type, typing.ForwardRef):
                # Strip out ForwardRef(' and ') as a hack for getting the
                # expected class
                type_for_forward_ref = str(nested_type)[12:-2]
                return all(
                    type_for_forward_ref == v.__class__.__name__
                    for v in actual_value
                )

            return all(
                self._validate_list_types(v, nested_type) for v in actual_value
            )
        else:
            return isinstance(actual_value, expected_type) 
开发者ID:abatilo,项目名称:typed-json-dataclass,代码行数:25,代码来源:typed_json_dataclass.py

示例5: 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

示例6: test_same_forward_ref

# 需要导入模块: import typing [as 别名]
# 或者: from typing import ForwardRef [as 别名]
def test_same_forward_ref():
    fr1 = ForwardRef('a')
    fr2 = ForwardRef('a')
    unify_helper(fr1, fr2, fr1)
    unify_helper(fr1, fr2, fr2) 
开发者ID:pyta-uoft,项目名称:pyta,代码行数:7,代码来源:test_unify.py

示例7: test_diff_forward_ref

# 需要导入模块: import typing [as 别名]
# 或者: from typing import ForwardRef [as 别名]
def test_diff_forward_ref():
    skip('The existing error msg does not apply to this situation')
    fr1 = ForwardRef('a')
    fr2 = ForwardRef('b')
    unify_helper(fr1, fr2, TypeFail("Attempted to unify forwardref  with non-ref")) 
开发者ID:pyta-uoft,项目名称:pyta,代码行数:7,代码来源:test_unify.py

示例8: test_one_forward_ref

# 需要导入模块: import typing [as 别名]
# 或者: from typing import ForwardRef [as 别名]
def test_one_forward_ref():
    fr = ForwardRef('a')
    unify_helper(fr, str, TypeFail("Attempted to unify forwardref  with non-ref"))


# Unify Tuples 
开发者ID:pyta-uoft,项目名称:pyta,代码行数:8,代码来源:test_unify.py

示例9: test_forward_ref

# 需要导入模块: import typing [as 别名]
# 或者: from typing import ForwardRef [as 别名]
def test_forward_ref(draw=False):
    tc.reset()
    t0 = tc.fresh_tvar()
    assert isinstance(tc.unify(ForwardRef('A'), ForwardRef('B')), TypeFail)
    assert tc.unify(ForwardRef('A'), ForwardRef('A')).getValue() == ForwardRef('A')
    assert tc.unify(t0, ForwardRef('A')).getValue() == ForwardRef('A')
    actual_set = tc_to_disjoint(tc)
    expected_set = [{'~_TV0', ForwardRef('A')}, {ForwardRef('B')}]
    compare_list_sets(actual_set, expected_set)
    if draw:
        gen_graph_from_nodes(tc._nodes) 
开发者ID:pyta-uoft,项目名称:pyta,代码行数:13,代码来源:test_tnode_structure.py

示例10: test_userdefn_inheritance_simple

# 需要导入模块: import typing [as 别名]
# 或者: from typing import ForwardRef [as 别名]
def test_userdefn_inheritance_simple(draw=False):
    src = """
    class A:
        pass

    class B:
        pass

    class C(A, B):
        pass

    a = A()
    b = B()
    c = C()
    """
    ast_mod, ti = cs._parse_text(src, reset=True)
    tc = ti.type_constraints
    a, b, c = [ti.lookup_typevar(node, node.name) for node
               in ast_mod.nodes_of_class(astroid.AssignName)]

    assert isinstance(tc.unify(a, b), TypeFail)
    assert tc.unify(c, a).getValue() == ForwardRef('C')
    assert isinstance(tc.unify(a, c), TypeFail)  # note that order matters!
    assert tc.unify(c, b).getValue() == ForwardRef('C')
    assert isinstance(tc.unify(b, c), TypeFail)

    actual_set = tc_to_disjoint(tc)
    expected_set = [
        {'~_TV0', Type[ForwardRef('A')]},
        {'~_TV1', Type[ForwardRef('B')]},
        {'~_TV2', Type[ForwardRef('C')]},
        {'~_TV3', ForwardRef('A')},
        {'~_TV4', ForwardRef('B')},
        {'~_TV5', ForwardRef('C')}
    ]

    # _TNodes should be unchanged after unification
    compare_list_sets(actual_set, expected_set)

    if draw:
        gen_graph_from_nodes(tc._nodes) 
开发者ID:pyta-uoft,项目名称:pyta,代码行数:43,代码来源:test_tnode_structure.py

示例11: test_functiondef_method

# 需要导入模块: import typing [as 别名]
# 或者: from typing import ForwardRef [as 别名]
def test_functiondef_method():
    program = \
        '''
        class A:

            def method(self, x):
                return x + 1
        '''
    module, inferer = cs._parse_text(program)
    for func_def in module.nodes_of_class(astroid.FunctionDef):
        assert lookup_type(inferer, func_def, func_def.argnames()[0]) == ForwardRef('A') 
开发者ID:pyta-uoft,项目名称:pyta,代码行数:13,代码来源:test_function_def_inference.py

示例12: test_functiondef_classmethod

# 需要导入模块: import typing [as 别名]
# 或者: from typing import ForwardRef [as 别名]
def test_functiondef_classmethod():
    program = \
        '''
        class A:

            @classmethod
            def method(cls, x):
                return x + 1
        '''
    module, inferer = cs._parse_text(program)
    for func_def in module.nodes_of_class(astroid.FunctionDef):
        assert lookup_type(inferer, func_def, func_def.argnames()[0]) == Type[ForwardRef('A')] 
开发者ID:pyta-uoft,项目名称:pyta,代码行数:14,代码来源:test_function_def_inference.py

示例13: test_class_with_init

# 需要导入模块: import typing [as 别名]
# 或者: from typing import ForwardRef [as 别名]
def test_class_with_init():
    program = """
    class Foo:
    
        def __init__(self):
            self.a = 5
    
    foo = Foo()
    """
    ast_mod, ti = cs._parse_text(program)
    for call_node in ast_mod.nodes_of_class(astroid.Call):
        assert isinstance(call_node.inf_type.getValue(), ForwardRef)
        assert call_node.inf_type.getValue() == ForwardRef('Foo') 
开发者ID:pyta-uoft,项目名称:pyta,代码行数:15,代码来源:test_initializer.py

示例14: test_class_without_init

# 需要导入模块: import typing [as 别名]
# 或者: from typing import ForwardRef [as 别名]
def test_class_without_init():
    program = """
    class Foo:
        def fee(self):
            return 1

    foo = Foo()
    """
    ast_mod, ti = cs._parse_text(program)
    for call_node in ast_mod.nodes_of_class(astroid.Call):
        assert isinstance(call_node.inf_type.getValue(), ForwardRef)
        assert call_node.inf_type.getValue() == ForwardRef('Foo') 
开发者ID:pyta-uoft,项目名称:pyta,代码行数:14,代码来源:test_initializer.py

示例15: _set_module_environment

# 需要导入模块: import typing [as 别名]
# 或者: from typing import ForwardRef [as 别名]
def _set_module_environment(self, node: astroid.Module) -> None:
        """Method to set environment of a Module node."""
        node.type_environment = Environment()
        for name in node.globals:
            if not any(isinstance(elt, (astroid.ImportFrom, astroid.Import)) for elt in node.globals[name]):
                new_tvar = self.type_constraints.fresh_tvar(node.globals[name][0])
                if any(isinstance(elt, astroid.ClassDef) for elt in node.globals[name]):
                    self.type_constraints.unify(new_tvar, Type[ForwardRef(name)], node)
                node.type_environment.globals[name] = new_tvar
        self._populate_local_env(node) 
开发者ID:pyta-uoft,项目名称:pyta,代码行数:12,代码来源:type_inference_visitor.py


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