Feature support overview
Mypy supports most Python features, but some dynamic patterns have limitations. For a comprehensive list of unsupported features, see:Unsupported Python features on the mypy wiki
Runtime definition of methods and functions
By default, mypy will report errors if you add functions or methods to classes/modules outside their definition.Example issue
Workarounds
You can work around this limitation in several ways:from typing import Any
class MyClass:
pass
obj: Any = MyClass()
obj.new_method() # OK, Any bypasses type checking
class MyClass:
pass
def new_method(self) -> None:
print("dynamic method")
setattr(MyClass, "new_method", new_method)
obj = MyClass()
obj.new_method() # Mypy won't see this at type-check time
from typing import cast, Protocol
class HasNewMethod(Protocol):
def new_method(self) -> None: ...
class MyClass:
pass
MyClass.new_method = lambda self: print("dynamic method")
obj = cast(HasNewMethod, MyClass())
obj.new_method() # OK
Important considerations
Static vs. runtime checking
Mypy performs static type checking only. It doesn’t add any runtime type checks to your code.
- Dynamic attribute assignment works at runtime
- Mypy just won’t be able to type-check it
- You need to be more careful to avoid runtime errors
Best practices
When using dynamic features:Recommended approaches
For libraries
If you’re writing a library that uses metaprogramming:- Provide type stubs (
.pyifiles) describing the final API - Write a mypy plugin to help type-check usage
- Document which features mypy can and can’t verify
For applications
If you’re writing application code:- Avoid dynamic features when possible
- Use protocols to describe dynamic interfaces
- Isolate dynamic code to specific modules
- Use
# type: ignoresparingly for known dynamic patterns
Example: Controlled dynamic behavior
This pattern provides runtime flexibility while maintaining type safety.
Performance considerations
Mypy’s static analysis performs no runtime checks:For runtime type checking, consider libraries like:
pydanticfor data validationtypeguardfor runtime type checkingbeartypefor zero-overhead runtime checks
Additional resources
For more information:- Mypy issue tracker - Report bugs and feature requests
- Typing discussions - Python typing questions
- Mypy wiki - Additional documentation