本文整理匯總了Python中typing._GenericAlias方法的典型用法代碼示例。如果您正苦於以下問題:Python typing._GenericAlias方法的具體用法?Python typing._GenericAlias怎麽用?Python typing._GenericAlias使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類typing
的用法示例。
在下文中一共展示了typing._GenericAlias方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: tc_to_disjoint
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import _GenericAlias [as 別名]
def tc_to_disjoint(tc: TypeConstraints) -> List[Set[Union[type, str]]]:
tnode_list = tc._nodes.copy()
disjoint_set = []
while tnode_list:
cur_tnode = tnode_list[0]
new_set = set()
open_nodes = [cur_tnode]
visited_nodes = []
while open_nodes:
cur_open_node = open_nodes[0]
if isinstance(cur_open_node.type, TypeVar) or isinstance(cur_open_node.type, _GenericAlias):
new_set.add(str(cur_open_node.type))
else:
new_set.add(cur_open_node.type)
for e in cur_open_node.adj_list:
if e[0] not in visited_nodes and e[0] not in open_nodes:
open_nodes.append(e[0])
visited_nodes.append(cur_open_node)
if cur_open_node in tnode_list:
tnode_list.remove(cur_open_node)
open_nodes.remove(cur_open_node)
disjoint_set.append(new_set)
return disjoint_set
示例2: test_annassign
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import _GenericAlias [as 別名]
def test_annassign(variables_annotations_dict):
"""Test whether types are being properly set for an AnnAssign node.
"""
program = f'class Student:\n'
for variable in variables_annotations_dict:
program += f' {variable}: {variables_annotations_dict[variable].__name__}\n'
program += f' def __init__(self):\n' \
f' pass\n'
module, inferer = cs._parse_text(program)
for node in module.nodes_of_class(astroid.AnnAssign):
variable_type = lookup_type(inferer, node, node.target.name)
annotated_type = variables_annotations_dict[node.target.name]
if isinstance(variable_type, _GenericAlias):
assert _gorg(variable_type) == annotated_type
else:
assert variable_type == annotated_type
示例3: test_functiondef_annotated_simple_return
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import _GenericAlias [as 別名]
def test_functiondef_annotated_simple_return(functiondef_node):
"""Test whether type annotations are set properly for a FunctionDef node representing a function definition
with type annotations."""
arg_names = [arg.name for arg in functiondef_node.args.args]
assume(functiondef_node.name not in arg_names)
for arg in functiondef_node.args.args:
assume(arg_names.count(arg.name) == 1)
module, inferer = cs._parse_text(functiondef_node)
functiondef_node = next(module.nodes_of_class(astroid.FunctionDef))
# arguments and annotations are not changing, so test this once.
for i in range(len(functiondef_node.args.annotations)):
arg_name = functiondef_node.args.args[i].name
expected_type = inferer.type_constraints.resolve(functiondef_node.type_environment.lookup_in_env(arg_name)).getValue()
# need to do by name because annotations must be name nodes.
if isinstance(expected_type, _GenericAlias):
assert _gorg(expected_type).__name__ == functiondef_node.args.annotations[i].name
else:
assert expected_type.__name__ == functiondef_node.args.annotations[i].name
# test return type
return_node = functiondef_node.body[0].value
expected_rtype = inferer.type_constraints.resolve(functiondef_node.type_environment.lookup_in_env(return_node.name)).getValue()
if isinstance(expected_rtype, _GenericAlias):
assert _gorg(expected_rtype).__name__ == functiondef_node.returns.name
else:
assert expected_rtype.__name__ == functiondef_node.returns.name
示例4: resolve
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import _GenericAlias [as 別名]
def resolve(self, t: type) -> TypeResult:
"""Return the concrete type or set representative associated with the given type.
"""
if isinstance(t, _GenericAlias):
if t.__args__ is not None:
res_args = [self.resolve(arg) for arg in t.__args__]
return _wrap_generic_meta(t, failable_collect(res_args))
else:
return TypeInfo(t)
elif isinstance(t, TypeVar):
try:
repr = self.find_repr(self.type_to_tnode[str(t)])
if repr and repr.type is not t:
if any(elt is t for elt in getattr(repr.type, '__args__', [])):
return TypeInfo(t)
else:
return self.resolve(repr.type)
except KeyError:
return TypeInfo(t)
return TypeInfo(t)
示例5: _generic_to_annotation
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import _GenericAlias [as 別名]
def _generic_to_annotation(ann_node_type: type, node: NodeNG) -> TypeResult:
if (isinstance(ann_node_type, _GenericAlias) and
ann_node_type is getattr(typing, getattr(ann_node_type, '_name', '') or '', None)):
if ann_node_type == Dict:
ann_type = wrap_container(ann_node_type, Any, Any)
elif ann_node_type == Tuple:
# TODO: Add proper support for multi-parameter Tuples
ann_type = wrap_container(ann_node_type, Any)
else:
ann_type = wrap_container(ann_node_type, Any)
elif isinstance(ann_node_type, _GenericAlias):
parsed_args = []
for arg in ann_node_type.__args__:
_generic_to_annotation(arg, node) >> parsed_args.append
ann_type = wrap_container(ann_node_type, *parsed_args)
else:
try:
_type_check(ann_node_type, '')
except TypeError:
return TypeFailAnnotationInvalid(node)
else:
ann_type = TypeInfo(ann_node_type)
return ann_type
示例6: __class_getitem__
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import _GenericAlias [as 別名]
def __class_getitem__(cls, params):
if not isinstance(params, tuple):
params = (params,)
if not params and cls is not Tuple:
raise TypeError(
"Parameter list to {}[...] cannot be empty".format(cls.__qualname__))
msg = "Parameters to generic types must be types."
params = tuple(_type_check(p, msg) for p in params)
if cls is Protocol:
# Generic can only be subscripted with unique type variables.
if not all(isinstance(p, TypeVar) for p in params):
i = 0
while isinstance(params[i], TypeVar):
i += 1
raise TypeError(
"Parameters to Protocol[...] must all be type variables."
" Parameter {} is {}".format(i + 1, params[i]))
if len(set(params)) != len(params):
raise TypeError(
"Parameters to Protocol[...] must all be unique")
else:
# Subscripting a regular Generic subclass.
_check_generic(cls, params)
return _GenericAlias(cls, params)
示例7: detect_list_type
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import _GenericAlias [as 別名]
def detect_list_type(typ):
"""
Internal method to detect whether an abstract type is a List-type, and if so
returns the type of the list elements. Returns `None` otherwise.
:param field_type: The abstract type to be analyzed.
:return: The type of the list elements, or `None`.
"""
# Read more about this issue here:
# https://github.com/swagger-api/swagger-codegen/issues/8921
if _sys.version_info >= (3, 7):
if type(typ) is _typing._GenericAlias and typ._name == "List":
return typ.__args__[0]
elif _sys.version_info >= (3, 0):
try:
if (type(typ) is _typing.GenericMeta and
(hasattr(typ, "__extra__") and typ.__extra__ is list)):
return typ.__args__[0]
except AttributeError:
pass
if hasattr(typ, "__origin__") and typ.__origin__ is _typing.List:
return typ.__args__[0]
示例8: is_type_variable
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import _GenericAlias [as 別名]
def is_type_variable(typ):
"""
Determines whether an object is a type variable.
:param typ: The variable to be analyzed.
:return: `True` if variable is either an elementary type or an abstract type.
"""
# All elementary types are simple
if type(typ) is type:
return True
# Now we must handle "abstract" types (i.e., List[int] for instance)
# NOTE: Since our framework only uses List[xxx] we can limit to this subcase
# for the moment (avoid unpredictability).
_only_allow_list_generic_objects = True
if _sys.version_info >= (3, 7):
return type(typ) is _typing._GenericAlias and (
not _only_allow_list_generic_objects or
typ._name == "List")
elif _sys.version_info >= (3, 0):
try:
return type(typ) is _typing.GenericMeta and (
not _only_allow_list_generic_objects or
(hasattr(typ, "__extra__") and typ.__extra__ is list)
)
except AttributeError:
pass
return hasattr(typ, "__origin__") and (
not _only_allow_list_generic_objects or
typ.__origin__ is _typing.List
)
# default case is that `typ` is probably not a type reference
return False
# =============================================================================
示例9: get_attribute_class
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import _GenericAlias [as 別名]
def get_attribute_class(self, t: type) -> Tuple[str, type, bool]:
"""Check for and return name and type of class represented by type t."""
is_inst_expr = True
# TypeVar; e.g., 'TypeVar('_T1')' corresponding to a function argument
if isinstance(t, TypeVar):
return t.__name__, t, None
# Class type: e.g., 'Type[ForwardRef('A')]'
if getattr(t, '__origin__', None) is type:
class_type = t.__args__[0]
is_inst_expr = False
# Instance of class or builtin type; e.g., 'ForwardRef('A')' or 'int'
else:
class_type = t
if isinstance(class_type, ForwardRef):
class_name = class_type.__forward_arg__
elif isinstance(class_type, _GenericAlias):
class_name = class_type._name
else:
class_name = getattr(t, '__name__', None)
# TODO: the condition below is too general
if class_name is not None and class_name not in self.type_store.classes:
class_name = class_name.lower()
return class_name, class_type, is_inst_expr
示例10: _get_name
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import _GenericAlias [as 別名]
def _get_name(t: type) -> str:
"""If t is associated with a class, return the name of the class; otherwise, return a string repr. of t"""
if isinstance(t, ForwardRef):
return t.__forward_arg__
elif isinstance(t, type):
return t.__name__
elif isinstance(t, _GenericAlias):
return '{} of {}'.format(_get_name(t.__origin__),
', '.join(_get_name(arg) for arg in t.__args__))
else:
return str(t)
示例11: wrap_container
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import _GenericAlias [as 別名]
def wrap_container(container_type: _GenericAlias, *args: type) -> TypeResult:
"""Return instance of type container_type with type variable arguments args, wrapped in instance of TypeInfo."""
return TypeInfo(container_type.copy_with(args))
示例12: _get_poly_vars
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import _GenericAlias [as 別名]
def _get_poly_vars(t: type) -> Set[str]:
"""Return a set consisting of the names of all TypeVars within t"""
if isinstance(t, TypeVar) and t.__name__ in _TYPESHED_TVARS:
return set([t.__name__])
elif isinstance(t, _GenericAlias) and t.__args__:
pvars = set()
for arg in t.__args__:
pvars.update(_get_poly_vars(arg))
return pvars
return set()
示例13: is_concrete
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import _GenericAlias [as 別名]
def is_concrete(self, t: type) -> bool:
if isinstance(t, _GenericAlias):
return all([self.is_concrete(arg) for arg in t.__args__])
else:
return not isinstance(t, TypeVar)
示例14: _type_eval
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import _GenericAlias [as 別名]
def _type_eval(self, t: type) -> TypeResult:
"""Evaluate a type. Used for tuples."""
if isinstance(t, TuplePlus):
return t.eval_type(self)
if isinstance(t, TypeVar):
return self.resolve(t)
if isinstance(t, _GenericAlias) and t.__args__ is not None:
inf_args = (self._type_eval(argument) for argument in t.__args__)
return wrap_container(t, *inf_args)
else:
return TypeInfo(t)
示例15: _collect_tvars
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import _GenericAlias [as 別名]
def _collect_tvars(type: type) -> List[type]:
if isinstance(type, TypeVar):
return [type]
elif isinstance(type, _GenericAlias) and type.__args__:
return sum([_collect_tvars(arg) for arg in type.__args__], [])
else:
return []