How to use mypy - 10 common examples

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 / View on Github external
# We need to record this check to generate protocol fine-grained dependencies.
    TypeState.record_protocol_subtype_check(left.type, right.type)
    assuming = right.type.assuming_proper if proper_subtype else right.type.assuming
    for (l, r) in reversed(assuming):
        if (mypy.sametypes.is_same_type(l, left)
                and mypy.sametypes.is_same_type(r, right)):
            return True
    with pop_on_exit(assuming, left, right):
        for member in right.type.protocol_members:
            # nominal subtyping currently ignores '__init__' and '__new__' signatures
            if member in ('__init__', '__new__'):
            ignore_names = member != '__call__'  # __call__ can be passed kwargs
            # The third argument below indicates to what self type is bound.
            # We always bind self to the subtype. (Similarly to nominal types).
            supertype = get_proper_type(find_member(member, right, left))
            assert supertype is not None
            subtype = get_proper_type(find_member(member, left, left))
            # Useful for debugging:
            # print(member, 'of', left, 'has type', subtype)
            # print(member, 'of', right, 'has type', supertype)
            if not subtype:
                return False
            if not proper_subtype:
                # Nominal check currently ignores arg names
                # NOTE: If we ever change this, be sure to also change the call to
                # SubtypeVisitor.build_subtype_kind(...) down below.
                is_compat = is_subtype(subtype, supertype, ignore_pos_arg_names=ignore_names)
                is_compat = is_proper_subtype(subtype, supertype)
            if not is_compat:
                return False
github python / mypy / mypy / View on Github external
def try_handler(self,
                    body: List[ast27.stmt],
                    handlers: List[ast27.ExceptHandler],
                    orelse: List[ast27.stmt],
                    finalbody: List[ast27.stmt],
                    lineno: int) -> TryStmt:
        vs = []  # type: List[Optional[NameExpr]]
        for item in handlers:
            if is None:
            elif isinstance(, Name):
      "Sorry, `except , ` is not supported",
                          item.lineno, item.col_offset)
        types = [self.visit(h.type) for h in handlers]
        handlers_ = [self.as_required_block(h.body, h.lineno) for h in handlers]

        return TryStmt(self.as_required_block(body, lineno),
                       self.as_block(orelse, lineno),
                       self.as_block(finalbody, lineno))
github python / mypy / mypy / View on Github external
def make_namedtuple_init(self, info: TypeInfo, items: List[str],
                             types: List[Type]) -> FuncDef:
        args = [self.make_argument(item, type) for item, type in zip(items, types)]
        # TODO: Make sure that the self argument name is not visible?
        args = [Argument(Var('__self'), NoneTyp(), None, ARG_POS)] + args
        arg_kinds = [arg.kind for arg in args]
        signature = CallableType([cast(Type, None)] + types,
                                 ['__self'] + items,
        func = FuncDef('__init__',
                       typ=signature) = info
        return func
github python / mypy / mypy / View on Github external
if '.' in name:
                module_name = name.rsplit('.', 1)[0]
                module_name = '__main__'

        if typevars:
            v = []  # type: List[TypeVarDef]
            for id, n in enumerate(typevars, 1):
                if variances:
                    variance = variances[id - 1]
                    variance = COVARIANT
                v.append(TypeVarDef(n, id, [], self.o, variance=variance))
            class_def.type_vars = v

        info = TypeInfo(SymbolTable(), class_def, module_name)
        if mro is None:
            mro = []
            if name != 'builtins.object':
        info.mro = [info] + mro
        if bases is None:
            if mro:
                # By default, assume that there is a single non-generic base.
                bases = [Instance(mro[0], [])]
                bases = []
        info.bases = bases

        return info
github python / mypy / mypy / View on Github external
def visit_namedtuple_expr(self, e: NamedTupleExpr) -> Type:
        # TODO: Perhaps return a type object type?
        return AnyType()
github QQuick / Transcrypt / transcrypt / modules / org / transcrypt / type_check / mypy-lang-0.4.4_and_api / mypy / View on Github external
                if specifier.key not in mapping:
                    self.msg.key_not_in_mapping(specifier.key, replacements)
                rep_type = mapping[specifier.key]
                expected_type = self.conversion_type(specifier.type, replacements)
                if expected_type is None:
                self.chk.check_subtype(rep_type, expected_type, replacements,
                                       'expression has type',
                                       'placeholder with key \'%s\' has type' % specifier.key)
            rep_type = self.accept(replacements)
            dict_type = self.chk.named_generic_type('builtins.dict',
                                            [AnyType(), AnyType()])
            self.chk.check_subtype(rep_type, dict_type, replacements,
                                   'expression has type', 'expected type for mapping is')
github python / mypy / mypy / View on Github external
def check_getattr_method(self, typ: CallableType, context: Context) -> None:
        method_type = CallableType([AnyType(), self.named_type('builtins.str')],
                                   [nodes.ARG_POS, nodes.ARG_POS],
                                   [None, None],
        if not is_subtype(typ, method_type):
            self.msg.invalid_signature(typ, context)
github python / mypy / mypy / View on Github external
for t in arg_types):
      "Ellipses cannot accompany other argument types "
                          "in function type signature", lineno, n.col_offset)
            elif len(arg_types) > len(arg_kinds):
      'Type signature has too many arguments', lineno, n.col_offset,
            elif len(arg_types) < len(arg_kinds):
      'Type signature has too few arguments', lineno, n.col_offset,
                func_type = CallableType([a if a is not None else
                                          AnyType(TypeOfAny.unannotated) for a in arg_types],
                                         return_type if return_type is not None else

        func_def = FuncDef(,
                       self.as_required_block(n.body, lineno),
        if isinstance(func_def.type, CallableType):
            # does some in-place modifications we want to avoid
            func_def.unanalyzed_type = func_def.type.copy_modified()
        if is_coroutine:
            func_def.is_coroutine = True
        if func_type is not None:
            func_type.definition = func_def
            func_type.line = lineno

        if n.decorator_list:
github python / mypy / mypy / View on Github external
def is_generator_return_type(self, typ: Type, is_coroutine: bool) -> bool:
        """Is `typ` a valid type for a generator/coroutine?

        True if `typ` is a *supertype* of Generator or Awaitable.
        Also true it it's *exactly* AwaitableGenerator (modulo type parameters).
        if is_coroutine:
            # This means we're in Python 3.5 or later.
            at = self.named_generic_type('typing.Awaitable', [AnyType()])
            if is_subtype(at, typ):
                return True
            gt = self.named_generic_type('typing.Generator', [AnyType(), AnyType(), AnyType()])
            if is_subtype(gt, typ):
                return True
        return isinstance(typ, Instance) and typ.type.fullname() == 'typing.AwaitableGenerator'
github QQuick / Transcrypt / transcrypt / modules / org / transcrypt / type_check / mypy-lang-0.4.4_and_api / mypy / View on Github external
def check_reverse_op_method(self, defn: FuncItem, typ: CallableType,
                                method: str) -> None:
        """Check a reverse operator method such as __radd__."""

        # This used to check for some very obscure scenario.  It now
        # just decides whether it's worth calling
        # check_overlapping_op_methods().

        if method in ('__eq__', '__ne__'):
            # These are defined for all objects => can't cause trouble.

        # With 'Any' or 'object' return type we are happy, since any possible
        # return value is valid.
        ret_type = typ.ret_type
        if isinstance(ret_type, AnyType):
        if isinstance(ret_type, Instance):
            if ret_type.type.fullname() == 'builtins.object':
        # Plausibly the method could have too few arguments, which would result
        # in an error elsewhere.
        if len(typ.arg_types) <= 2:
            # TODO check self argument kind

            # Check for the issue described above.
            arg_type = typ.arg_types[1]
            other_method = nodes.normal_from_reverse_op[method]
            if isinstance(arg_type, Instance):
                if not arg_type.type.has_readable_member(other_method):
            elif isinstance(arg_type, AnyType):