Python typing._GenericAlias() Examples

The following are 30 code examples of typing._GenericAlias(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module typing , or try the search function .
Example #1
Source File: test_tnode_structure.py    From pyta with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #2
Source File: test_annassign.py    From pyta with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #3
Source File: test_function_def_inference.py    From pyta with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #4
Source File: _typing.py    From pytablewriter with MIT License 6 votes vote down vote up
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) 
Example #5
Source File: base.py    From pyta with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #6
Source File: base.py    From pyta with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #7
Source File: _compat.py    From cattrs with MIT License 5 votes vote down vote up
def is_tuple(type):
        return type is Tuple or (
            type.__class__ is _GenericAlias
            and issubclass(type.__origin__, Tuple)
        ) 
Example #8
Source File: type_util.py    From pytypes with Apache License 2.0 5 votes vote down vote up
def is_Generic(tp):
    try:
        return isinstance(tp, typing.GenericMeta)
    except AttributeError:
        try:
            return issubclass(tp, typing.Generic)
# 			return isinstance(tp, typing._VariadicGenericAlias) and \
# 					tp.__origin__ is tuple
        except AttributeError:
            return False
        except TypeError:
            # Shall we accept _GenericAlias, i.e. Tuple, Union, etc?
            return isinstance(tp, typing._GenericAlias)
            #return False 
Example #9
Source File: type_util.py    From pytypes with Apache License 2.0 5 votes vote down vote up
def is_Callable(tp):
    try:
        return isinstance(tp, typing.CallableMeta)
    except AttributeError:
        try:
            return isinstance(tp, typing._GenericAlias) and \
                    _origin(tp) is collections.abc.Callable
        except AttributeError:
            raise #return False 
Example #10
Source File: type_util.py    From pytypes with Apache License 2.0 5 votes vote down vote up
def is_Generator(tp):
    if not _typing_3_7:
        return _origin(tp) is typing.Generator
    else:
        try:
            return isinstance(tp, typing._GenericAlias) and \
                    _origin(tp) is collections.abc.Generator
        except AttributeError:
            raise #return False 
Example #11
Source File: type_util.py    From pytypes with Apache License 2.0 5 votes vote down vote up
def is_Iterator(tp):
    if not _typing_3_7:
        return _origin(tp) is typing.Iterator
    else:
        try:
            return isinstance(tp, typing._GenericAlias) and \
                    _origin(tp) is collections.abc.Iterator
        except AttributeError:
            raise 
Example #12
Source File: _compat.py    From cattrs with MIT License 5 votes vote down vote up
def is_union_type(obj):
        return (
            obj is Union
            or isinstance(obj, _GenericAlias)
            and obj.__origin__ is Union
        ) 
Example #13
Source File: _compat.py    From cattrs with MIT License 5 votes vote down vote up
def is_sequence(type):
        return type is List or (
            type.__class__ is _GenericAlias
            and type.__origin__ is not Union
            and issubclass(type.__origin__, Sequence)
        ) 
Example #14
Source File: _compat.py    From cattrs with MIT License 5 votes vote down vote up
def is_frozenset(type):
        return type.__class__ is _GenericAlias and issubclass(
            type.__origin__, FrozenSet
        ) 
Example #15
Source File: _compat.py    From cattrs with MIT License 5 votes vote down vote up
def is_mutable_set(type):
        return type.__class__ is _GenericAlias and issubclass(
            type.__origin__, MutableSet
        ) 
Example #16
Source File: api_resource_metaclass.py    From codepost-python with GNU Lesser General Public License v3.0 5 votes vote down vote up
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

# ============================================================================= 
Example #17
Source File: helpers.py    From mashumaro with Apache License 2.0 5 votes vote down vote up
def is_generic(t):
    if PY_37 or PY_38:
        # noinspection PyProtectedMember
        # noinspection PyUnresolvedReferences
        return t.__class__ is typing._GenericAlias
    elif PY_36:
        # noinspection PyUnresolvedReferences
        return issubclass(t.__class__, typing.GenericMeta)
    else:
        raise NotImplementedError 
Example #18
Source File: _typing.py    From pytablewriter with MIT License 5 votes vote down vote up
def __getitem__(self, parameters):
            item = typing._type_check(parameters,
                                      '{} accepts only single type'.format(self._name))
            return _GenericAlias(self, (item,)) 
Example #19
Source File: _typing.py    From pytablewriter with MIT License 5 votes vote down vote up
def __getitem__(self, parameters):
            return _GenericAlias(self, parameters) 
Example #20
Source File: _typing.py    From pytablewriter with MIT License 5 votes vote down vote up
def _strip_annotations(t):
        """Strips the annotations from a given type.
        """
        if isinstance(t, _AnnotatedAlias):
            return _strip_annotations(t.__origin__)
        if isinstance(t, typing._GenericAlias):
            stripped_args = tuple(_strip_annotations(a) for a in t.__args__)
            if stripped_args == t.__args__:
                return t
            res = t.copy_with(stripped_args)
            res._special = t._special
            return res
        return t 
Example #21
Source File: errors.py    From pyta with GNU General Public License v3.0 5 votes vote down vote up
def subscript_error_message(node: astroid.Subscript) -> str:
    # Accessing an element of a List with an incompatible index type (non-integers)
    subscript_concrete_type = (node.value.inf_type).getValue()
    if subscript_concrete_type is type(None):
        return f'NoneType is not subscriptable.'

    if not isinstance(subscript_concrete_type, _GenericAlias):
        subscript_gorg = subscript_concrete_type
    else:
        subscript_gorg = _gorg(subscript_concrete_type)

    if subscript_gorg is list:
        slice_type = _get_name(node.slice.inf_type.getValue())
        return f'You can only access elements of a list using an int. ' \
               f'You used {_correct_article(slice_type)}, {node.slice.value.as_string()}.'
    elif subscript_gorg is tuple:
        slice_type = _get_name(node.slice.inf_type.getValue())
        return f'You can only access elements of a tuple using an int. ' \
               f'You used {_correct_article(slice_type)}, {node.slice.value.as_string()}.'
    elif subscript_gorg is dict:
        slice_type = _get_name(node.slice.inf_type.getValue())
        return f'You tried to access an element of this dictionary using ' \
               f'{_correct_article(slice_type)}, {node.slice.value.as_string()}, ' \
               f'but the keys are of type {_get_name(subscript_concrete_type.__args__[0])}.'
    else:
        return f'You make a type annotation with an incorrect subscript.' 
Example #22
Source File: api_resource_metaclass.py    From codepost-python with GNU Lesser General Public License v3.0 5 votes vote down vote up
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] 
Example #23
Source File: type_inference_visitor.py    From pyta with GNU General Public License v3.0 5 votes vote down vote up
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 
Example #24
Source File: utils.py    From pyta with GNU General Public License v3.0 5 votes vote down vote up
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) 
Example #25
Source File: base.py    From pyta with GNU General Public License v3.0 5 votes vote down vote up
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)) 
Example #26
Source File: base.py    From pyta with GNU General Public License v3.0 5 votes vote down vote up
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() 
Example #27
Source File: base.py    From pyta with GNU General Public License v3.0 5 votes vote down vote up
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) 
Example #28
Source File: base.py    From pyta with GNU General Public License v3.0 5 votes vote down vote up
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) 
Example #29
Source File: base.py    From pyta with GNU General Public License v3.0 5 votes vote down vote up
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 [] 
Example #30
Source File: type_util.py    From pytypes with Apache License 2.0 5 votes vote down vote up
def is_Tuple(tp):
    try:
        return isinstance(tp, typing.TupleMeta)
    except AttributeError:
        try:
            return isinstance(tp, typing._GenericAlias) and \
                    tp.__origin__ is tuple
        except AttributeError:
            return False