Welcome to mypy documentation!¶
Mypy is a static type checker for Python.
Type checkers help ensure that you’re using variables and functions in your code correctly. With mypy, add type hints (PEP 484) to your Python programs, and mypy will warn you when you use those types incorrectly.
Python is a dynamic language, so usually you’ll only see errors in your code when you attempt to run it. Mypy is a static checker, so it finds bugs in your programs without even running them!
Here is a small example to whet your appetite:
number = input("What is your favourite number?")
print("It is", number + 1) # error: Unsupported operand types for + ("str" and "int")
Adding type hints for mypy does not interfere with the way your program would otherwise run. Think of type hints as similar to comments! You can always use the Python interpreter to run your code, even if mypy reports errors.
Mypy is designed with gradual typing in mind. This means you can add type hints to your code base slowly and that you can always fall back to dynamic typing when static typing is not convenient.
Mypy has a powerful and easy-to-use type system, supporting features such as type inference, generics, callable types, tuple types, union types, structural subtyping and more. Using mypy will make your programs easier to understand, debug, and maintain.
Note
Although mypy is production ready, there may be occasional changes that break backward compatibility. The mypy development team tries to minimize the impact of changes to user code. In case of a major breaking change, mypy’s major version will be bumped.
Contents¶
- Built-in types
- Type inference and type annotations
- Kinds of types
- Class basics
- Annotation issues at runtime
- String literal types and type comments
- Future annotations import (PEP 563)
- typing.TYPE_CHECKING
- Class name forward references
- Import cycles
- Using classes that are generic in stubs but not at runtime
- Using types defined in stubs but not at runtime
- Using generic builtins
- Using X | Y syntax for Unions
- Using new additions to the typing module
- Protocols and structural subtyping
- Dynamically typed code
- Type narrowing
- Duck type compatibility
- Stub files
- Generics
- Defining generic classes
- Defining subclasses of generic classes
- Generic functions
- Generic methods and generic self
- Automatic self types using typing.Self
- Variance of generic types
- Type variables with upper bounds
- Type variables with value restriction
- Declaring decorators
- Generic protocols
- Generic type aliases
- Generic class internals
- More types
- Literal types and Enums
- TypedDict
- Final names, methods and classes
- Metaclasses
- Running mypy and managing imports
- The mypy command line
- Specifying what to type check
- Optional arguments
- Config file
- Import discovery
- Platform configuration
- Disallow dynamic typing
- Untyped definitions and calls
- None and Optional handling
- Configuring warnings
- Miscellaneous strictness flags
- Configuring error messages
- Incremental mode
- Advanced options
- Report generation
- Enabling incomplete/experimental features
- Miscellaneous
- The mypy configuration file
- Config file format
- Per-module and global options
- Inverting option values
- Example
mypy.ini
- Import discovery
- Platform configuration
- Disallow dynamic typing
- Untyped definitions and calls
- None and Optional handling
- Configuring warnings
- Suppressing errors
- Miscellaneous strictness flags
- Configuring error messages
- Incremental mode
- Advanced options
- Report generation
- Miscellaneous
- Using a pyproject.toml file
- Example
pyproject.toml
- Inline configuration
- Mypy daemon (mypy server)
- Using installed packages
- Extending and integrating mypy
- Automatic stub generation (stubgen)
- Automatic stub testing (stubtest)
- Common issues and solutions
- No errors reported for obviously wrong code
- Spurious errors and locally silencing the checker
- Ignoring a whole file
- Issues with code at runtime
- Mypy runs are slow
- Types of empty collections
- Redefinitions with incompatible types
- Invariance vs covariance
- Declaring a supertype as variable type
- Complex type tests
- Python version and system platform checks
- Displaying the type of an expression
- Silencing linters
- Covariant subtyping of mutable protocol members is rejected
- Dealing with conflicting names
- Using a development mypy build
- Variables vs type aliases
- Incompatible overrides
- Unreachable code
- Narrowing and inner functions
- Supported Python features
- Error codes
- Error codes enabled by default
- Check that attribute exists [attr-defined]
- Check that attribute exists in each union item [union-attr]
- Check that name is defined [name-defined]
- Check that a variable is not used before it’s defined [used-before-def]
- Check arguments in calls [call-arg]
- Check argument types [arg-type]
- Check calls to overloaded functions [call-overload]
- Check validity of types [valid-type]
- Require annotation if variable type is unclear [var-annotated]
- Check validity of overrides [override]
- Check that function returns a value [return]
- Check that functions don’t have empty bodies outside stubs [empty-body]
- Check that return value is compatible [return-value]
- Check types in assignment statement [assignment]
- Check that assignment target is not a method [method-assign]
- Check type variable values [type-var]
- Check uses of various operators [operator]
- Check indexing operations [index]
- Check list items [list-item]
- Check dict items [dict-item]
- Check TypedDict items [typeddict-item]
- Check TypedDict Keys [typeddict-unknown-key]
- Check that type of target is known [has-type]
- Check for an issue with imports [import]
- Check that import target can be found [import-not-found]
- Check that import target can be found [import-untyped]
- Check that each name is defined once [no-redef]
- Check that called function returns a value [func-returns-value]
- Check instantiation of abstract classes [abstract]
- Safe handling of abstract type object types [type-abstract]
- Check that call to an abstract method via super is valid [safe-super]
- Check the target of NewType [valid-newtype]
- Check the return type of __exit__ [exit-return]
- Check that naming is consistent [name-match]
- Check that literal is used where expected [literal-required]
- Check that overloaded functions have an implementation [no-overload-impl]
- Check that coroutine return value is used [unused-coroutine]
- Warn about top level await expressions [top-level-await]
- Warn about await expressions used outside of coroutines [await-not-async]
- Check types in assert_type [assert-type]
- Check that function isn’t used in boolean context [truthy-function]
- Check that string formatting/interpolation is type-safe [str-format]
- Check for implicit bytes coercions [str-bytes-safe]
- Check that overloaded functions don’t overlap [overload-overlap]
- Notify about an annotation in an unchecked function [annotation-unchecked]
- Decorator preceding property not supported [prop-decorator]
- Report syntax errors [syntax]
- Miscellaneous checks [misc]
- Error codes for optional checks
- Check that type arguments exist [type-arg]
- Check that every function has an annotation [no-untyped-def]
- Check that cast is not redundant [redundant-cast]
- Check that methods do not have redundant Self annotations [redundant-self]
- Check that comparisons are overlapping [comparison-overlap]
- Check that no untyped functions are called [no-untyped-call]
- Check that function does not return Any value [no-any-return]
- Check that types have no Any components due to missing imports [no-any-unimported]
- Check that statement or expression is unreachable [unreachable]
- Check that expression is redundant [redundant-expr]
- Warn about variables that are defined only in some execution paths [possibly-undefined]
- Check that expression is not implicitly true in boolean context [truthy-bool]
- Check that iterable is not implicitly true in boolean context [truthy-iterable]
- Check that
# type: ignore
include an error code [ignore-without-code] - Check that awaitable return value is used [unused-awaitable]
- Check that
# type: ignore
comment is used [unused-ignore] - Check that
@override
is used when overriding a base class method [explicit-override] - Check that overrides of mutable attributes are safe [mutable-override]
- Check that
reveal_type
is imported from typing or typing_extensions [unimported-reveal] - Check that
TypeIs
narrows types [narrowed-type-not-subtype]
- Additional features
- Frequently Asked Questions
- Why have both dynamic and static typing?
- Would my project benefit from static typing?
- Can I use mypy to type check my existing Python code?
- Will static typing make my programs run faster?
- Is mypy free?
- Can I use duck typing with mypy?
- I like Python and I have no need for static typing
- How are mypy programs different from normal Python?
- How is mypy different from Cython?
- Does it run on PyPy?
- Mypy is a cool project. Can I help?