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 / subtypes.py 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__'):
                continue
            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)
            else:
                is_compat = is_proper_subtype(subtype, supertype)
            if not is_compat:
                return False
github python / mypy / mypy / fastparse2.py 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 item.name is None:
                vs.append(None)
            elif isinstance(item.name, Name):
                vs.append(NameExpr(item.name.id))
            else:
                self.fail("Sorry, `except , ` is not supported",
                          item.lineno, item.col_offset)
                vs.append(None)
        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),
                       vs,
                       types,
                       handlers_,
                       self.as_block(orelse, lineno),
                       self.as_block(finalbody, lineno))
github python / mypy / mypy / semanal.py 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,
                                 arg_kinds,
                                 ['__self'] + items,
                                 NoneTyp(),
                                 self.named_type('__builtins__.function'),
                                 name=info.name())
        func = FuncDef('__init__',
                       args,
                       Block([]),
                       typ=signature)
        func.info = info
        return func
github python / mypy / mypy / typefixture.py View on Github external
if '.' in name:
                module_name = name.rsplit('.', 1)[0]
            else:
                module_name = '__main__'

        if typevars:
            v = []  # type: List[TypeVarDef]
            for id, n in enumerate(typevars, 1):
                if variances:
                    variance = variances[id - 1]
                else:
                    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':
                mro.append(self.oi)
        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], [])]
            else:
                bases = []
        info.bases = bases

        return info
github python / mypy / mypy / checker.py 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 / checkstrformat.py View on Github external
continue
                if specifier.key not in mapping:
                    self.msg.key_not_in_mapping(specifier.key, replacements)
                    return
                rep_type = mapping[specifier.key]
                expected_type = self.conversion_type(specifier.type, replacements)
                if expected_type is None:
                    return
                self.chk.check_subtype(rep_type, expected_type, replacements,
                                       messages.INCOMPATIBLE_TYPES_IN_STR_INTERPOLATION,
                                       'expression has type',
                                       'placeholder with key \'%s\' has type' % specifier.key)
        else:
            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,
                                   messages.FORMAT_REQUIRES_MAPPING,
                                   'expression has type', 'expected type for mapping is')
github python / mypy / mypy / checker.py 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],
                                   AnyType(),
                                   self.named_type('builtins.function'))
        if not is_subtype(typ, method_type):
            self.msg.invalid_signature(typ, context)
github python / mypy / mypy / fastparse.py View on Github external
for t in arg_types):
                self.fail("Ellipses cannot accompany other argument types "
                          "in function type signature", lineno, n.col_offset)
            elif len(arg_types) > len(arg_kinds):
                self.fail('Type signature has too many arguments', lineno, n.col_offset,
                          blocker=False)
            elif len(arg_types) < len(arg_kinds):
                self.fail('Type signature has too few arguments', lineno, n.col_offset,
                          blocker=False)
            else:
                func_type = CallableType([a if a is not None else
                                          AnyType(TypeOfAny.unannotated) for a in arg_types],
                                         arg_kinds,
                                         arg_names,
                                         return_type if return_type is not None else
                                         AnyType(TypeOfAny.unannotated),
                                         _dummy_fallback)

        func_def = FuncDef(n.name,
                       args,
                       self.as_required_block(n.body, lineno),
                       func_type)
        if isinstance(func_def.type, CallableType):
            # semanal.py 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 / checker.py 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
        else:
            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 / checker.py 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.
            return

        # 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):
            return
        if isinstance(ret_type, Instance):
            if ret_type.type.fullname() == 'builtins.object':
                return
        # 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):
                    return
            elif isinstance(arg_type, AnyType):