本文整理匯總了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)
示例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
示例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__
示例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)
示例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
示例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)
示例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"))
示例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
示例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)
示例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)
示例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')
示例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')]
示例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')
示例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')
示例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)