How to use the mypy.types.TypeVarType function in mypy

To help you get started, we’ve selected a few mypy examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github python / mypy / mypy / subtypes.py View on Github external
# This is unsound, we don't check the __init__ signature.
            return self._is_proper_subtype(left.item, right.item)
        if isinstance(right, CallableType):
            # This is also unsound because of __init__.
            return right.is_type_obj() and self._is_proper_subtype(left.item, right.ret_type)
        if isinstance(right, Instance):
            if right.type.fullname == 'builtins.type':
                # TODO: Strictly speaking, the type builtins.type is considered equivalent to
                #       Type[Any]. However, this would break the is_proper_subtype check in
                #       conditional_type_map for cases like isinstance(x, type) when the type
                #       of x is Type[int]. It's unclear what's the right way to address this.
                return True
            if right.type.fullname == 'builtins.object':
                return True
            item = left.item
            if isinstance(item, TypeVarType):
                item = get_proper_type(item.upper_bound)
            if isinstance(item, Instance):
                metaclass = item.type.metaclass_type
                return metaclass is not None and self._is_proper_subtype(metaclass, right)
        return False
github python / mypy / mypy / checkexpr.py View on Github external
def check_lst_expr(self, items: List[Expression], fullname: str,
                       tag: str, context: Context) -> Type:
        # Translate into type checking a generic function call.
        # Used for list and set expressions, as well as for tuples
        # containing star expressions that don't refer to a
        # Tuple. (Note: "lst" stands for list-set-tuple. :-)
        tvdef = TypeVarDef('T', -1, [], self.object_type())
        tv = TypeVarType(tvdef)
        constructor = CallableType(
            [tv],
            [nodes.ARG_STAR],
            [None],
            self.chk.named_generic_type(fullname, [tv]),
            self.named_type('builtins.function'),
            name=tag,
            variables=[tvdef])
        return self.check_call(constructor,
                               [(i.expr if isinstance(i, StarExpr) else i)
                                for i in items],
                               [(nodes.ARG_STAR if isinstance(i, StarExpr) else nodes.ARG_POS)
                                for i in items],
                               context)[0]
github python / mypy / mypy / typeanal.py View on Github external
and t.args and
                    not self.allow_unnormalized):
                self.fail(no_subscript_builtin_alias(fullname,
                                                     propose_alt=not self.defining_alias), t)
            if self.tvar_scope is not None:
                tvar_def = self.tvar_scope.get_binding(sym)
            else:
                tvar_def = None
            if isinstance(sym.node, TypeVarExpr) and tvar_def is not None and self.defining_alias:
                self.fail('Can\'t use bound type variable "{}"'
                          ' to define generic alias'.format(t.name), t)
                return AnyType(TypeOfAny.from_error)
            if isinstance(sym.node, TypeVarExpr) and tvar_def is not None:
                if len(t.args) > 0:
                    self.fail('Type variable "{}" used with arguments'.format(t.name), t)
                return TypeVarType(tvar_def, t.line)
            special = self.try_analyze_special_unbound_type(t, fullname)
            if special is not None:
                return special
            if isinstance(node, TypeAlias):
                self.aliases_used.add(fullname)
                all_vars = node.alias_tvars
                target = node.target
                an_args = self.anal_array(t.args)
                return expand_type_alias(target, all_vars, an_args, self.fail, node.no_args, t)
            elif isinstance(node, TypeInfo):
                return self.analyze_unbound_type_with_type_info(t, node)
            else:
                return self.analyze_unbound_type_without_type_info(t, sym, defining_literal)
        else:  # sym is None
            if self.third_pass:
                self.fail('Invalid type "{}"'.format(t.name), t)
github samuelcolvin / pydantic / pydantic / mypy.py View on Github external
and does not treat settings fields as optional.
        """
        ctx = self._ctx
        set_str = ctx.api.named_type('__builtins__.set', [ctx.api.named_type('__builtins__.str')])
        optional_set_str = UnionType([set_str, NoneType()])
        fields_set_argument = Argument(Var('_fields_set', optional_set_str), optional_set_str, None, ARG_OPT)
        construct_arguments = self.get_field_arguments(fields, typed=True, force_all_optional=False, use_alias=False)
        construct_arguments = [fields_set_argument] + construct_arguments

        obj_type = ctx.api.named_type('__builtins__.object')
        self_tvar_name = 'Model'
        tvar_fullname = ctx.cls.fullname + '.' + self_tvar_name
        tvd = TypeVarDef(self_tvar_name, tvar_fullname, -1, [], obj_type)
        self_tvar_expr = TypeVarExpr(self_tvar_name, tvar_fullname, [], obj_type)
        ctx.cls.info.names[self_tvar_name] = SymbolTableNode(MDEF, self_tvar_expr)
        self_type = TypeVarType(tvd)
        add_method(
            ctx,
            'construct',
            construct_arguments,
            return_type=self_type,
            self_type=self_type,
            tvar_def=tvd,
            is_classmethod=True,
        )
github python / mypy / mypy / typeanal.py View on Github external
if hook is not None:
                return hook(AnalyzeTypeContext(t, t, self))
            if (fullname in nongen_builtins
                    and t.args and
                    not self.allow_unnormalized):
                self.fail(no_subscript_builtin_alias(fullname,
                                                     propose_alt=not self.defining_alias), t)
            tvar_def = self.tvar_scope.get_binding(sym)
            if isinstance(sym.node, TypeVarExpr) and tvar_def is not None and self.defining_alias:
                self.fail('Can\'t use bound type variable "{}"'
                          ' to define generic alias'.format(t.name), t)
                return AnyType(TypeOfAny.from_error)
            if isinstance(sym.node, TypeVarExpr) and tvar_def is not None:
                if len(t.args) > 0:
                    self.fail('Type variable "{}" used with arguments'.format(t.name), t)
                return TypeVarType(tvar_def, t.line)
            special = self.try_analyze_special_unbound_type(t, fullname)
            if special is not None:
                return special
            if isinstance(node, TypeAlias):
                self.aliases_used.add(fullname)
                an_args = self.anal_array(t.args)
                disallow_any = self.options.disallow_any_generics and not self.is_typeshed_stub
                res = expand_type_alias(node, an_args, self.fail, node.no_args, t,
                                        unexpanded_type=t,
                                        disallow_any=disallow_any)
                # The only case where expand_type_alias() can return an incorrect instance is
                # when it is top-level instance, so no need to recurse.
                if (isinstance(res, Instance) and  # type: ignore[misc]
                        len(res.args) != len(res.type.type_vars) and
                        not self.defining_alias):
                    fix_instance(
github dry-python / classes / classes / contrib / mypy / typeclass_plugin.py View on Github external
def _adjust_typeclass_type(self, ctx, instance_type):
        unified = list(filter(
            # It means that function was defined without annotation
            # or with explicit `Any`, we prevent our Union from polution.
            # Because `Union[Any, int]` is just `Any`.
            # We also clear accidential type vars.
            self._filter_out_unified_types,
            [instance_type, ctx.type.args[0]],
        ))

        if not isinstance(instance_type, TypeVarType):
            ctx.type.args[0] = UnionType.make_union(unified)
github QQuick / Transcrypt / transcrypt / modules / org / transcrypt / type_check / mypy-lang-0.4.4_and_api / mypy / stats.py View on Github external
if any(is_complex(arg) for arg in t.args):
                    self.num_complex += 1
                else:
                    self.num_generic += 1
            else:
                self.num_simple += 1
        elif isinstance(t, Void):
            self.num_simple += 1
        elif isinstance(t, FunctionLike):
            self.num_function += 1
        elif isinstance(t, TupleType):
            if any(is_complex(item) for item in t.items):
                self.num_complex += 1
            else:
                self.num_tuple += 1
        elif isinstance(t, TypeVarType):
            self.num_typevar += 1
github QQuick / Transcrypt / transcrypt / modules / org / transcrypt / type_check / mypy-lang-0.4.4_and_api / mypy / typeanal.py View on Github external
# wrapping Anys: Union simplification will take care of that.
            return UnionType.make_simplified_union([self.visit_unbound_type(t), NoneTyp()])
        sym = self.lookup(t.name, t)
        if sym is not None:
            if sym.node is None:
                # UNBOUND_IMPORTED can happen if an unknown name was imported.
                if sym.kind != UNBOUND_IMPORTED:
                    self.fail('Internal error (node is None, kind={})'.format(sym.kind), t)
                return AnyType()
            fullname = sym.node.fullname()
            if sym.kind == BOUND_TVAR:
                if len(t.args) > 0:
                    self.fail('Type variable "{}" used with arguments'.format(
                        t.name), t)
                assert sym.tvar_def is not None
                return TypeVarType(sym.tvar_def, t.line)
            elif fullname == 'builtins.None':
                if experiments.STRICT_OPTIONAL:
                    return NoneTyp(is_ret_type=t.is_ret_type)
                else:
                    return Void()
            elif fullname == 'typing.Any':
                return AnyType()
            elif fullname == 'typing.Tuple':
                if len(t.args) == 2 and isinstance(t.args[1], EllipsisType):
                    # Tuple[T, ...] (uniform, variable-length tuple)
                    node = self.lookup_fqn_func('builtins.tuple')
                    tuple_info = cast(TypeInfo, node.node)
                    return Instance(tuple_info, [t.args[0].accept(self)], t.line)
                return self.tuple_type(self.anal_array(t.args))
            elif fullname == 'typing.Union':
                items = self.anal_array(t.args)
github python / mypy / mypy / checkexpr.py View on Github external
def check_lst_expr(self, items: List[Expression], fullname: str,
                       tag: str, context: Context) -> Type:
        # Translate into type checking a generic function call.
        # Used for list and set expressions, as well as for tuples
        # containing star expressions that don't refer to a
        # Tuple. (Note: "lst" stands for list-set-tuple. :-)
        tvdef = TypeVarDef('T', -1, [], self.object_type())
        tv = TypeVarType(tvdef)
        constructor = CallableType(
            [tv],
            [nodes.ARG_STAR],
            [None],
            self.chk.named_generic_type(fullname, [tv]),
            self.named_type('builtins.function'),
            name=tag,
            variables=[tvdef])
        return self.check_call(constructor,
                               [(i.expr if isinstance(i, StarExpr) else i)
                                for i in items],
                               [(nodes.ARG_STAR if isinstance(i, StarExpr) else nodes.ARG_POS)
                                for i in items],
                               context)[0]
github python / mypy / mypy / checker.py View on Github external
if fdef.type is None:
                            self.fail(messages.FUNCTION_TYPE_EXPECTED, fdef)
                        elif isinstance(fdef.type, CallableType):
                            if is_implicit_any(fdef.type.ret_type):
                                self.fail(messages.RETURN_TYPE_EXPECTED, fdef)
                            if any(is_implicit_any(t) for t in fdef.type.arg_types):
                                self.fail(messages.ARGUMENT_TYPE_EXPECTED, fdef)

                if name in nodes.reverse_op_method_set:
                    self.check_reverse_op_method(item, typ, name)
                elif name == '__getattr__':
                    self.check_getattr_method(typ, defn)

                # Refuse contravariant return type variable
                if isinstance(typ.ret_type, TypeVarType):
                    if typ.ret_type.variance == CONTRAVARIANT:
                        self.fail(messages.RETURN_TYPE_CANNOT_BE_CONTRAVARIANT,
                             typ.ret_type)

                # Check that Generator functions have the appropriate return type.
                if defn.is_generator:
                    if not self.is_generator_return_type(typ.ret_type, defn.is_coroutine):
                        self.fail(messages.INVALID_RETURN_TYPE_FOR_GENERATOR, typ)

                    # Python 2 generators aren't allowed to return values.
                    if (self.options.python_version[0] == 2 and
                            isinstance(typ.ret_type, Instance) and
                            typ.ret_type.type.fullname() == 'typing.Generator'):
                        if not isinstance(typ.ret_type.args[2], (Void, NoneTyp, AnyType)):
                            self.fail(messages.INVALID_GENERATOR_RETURN_ITEM_TYPE, typ)