We’ve just uploaded mypy 1.18.1 to the Python Package Index (PyPI). Mypy is a static type checker for Python. This release includes new features, performance improvements and bug fixes. You can install it as follows:
python3 -m pip install -U mypy
You can read the full documentation for this release on Read the Docs.
Mypy Performance Improvements
Mypy 1.18.1 includes numerous performance improvements, resulting in about 40% speedup compared to 1.17 when type checking mypy itself. In extreme cases, the improvement can be 10x or higher. The list below is an overview of the various mypy optimizations. Many mypyc improvements (discussed in a separate section below) also improve performance.
Type caching optimizations have a small risk of causing regressions. When reporting issues with unexpected inferred types, please also check if --disable-expression-cache will work around the issue, as it turns off some of these optimizations.
- Improve self check performance by 1.8% (Jukka Lehtosalo, PR 19768, 19769, 19770)
- Optimize fixed-format deserialization (Ivan Levkivskyi, PR 19765)
- Use macros to optimize fixed-format deserialization (Ivan Levkivskyi, PR 19757)
- Two additional micro‑optimizations (Ivan Levkivskyi, PR 19627)
- Another set of micro‑optimizations (Ivan Levkivskyi, PR 19633)
- Cache common types (Ivan Levkivskyi, PR 19621)
- Skip more method bodies in third‑party libraries for speed (Ivan Levkivskyi, PR 19586)
- Simplify the representation of callable types (Ivan Levkivskyi, PR 19580)
- Add cache for types of some expressions (Ivan Levkivskyi, PR 19505)
- Use cache for dictionary expressions (Ivan Levkivskyi, PR 19536)
- Use cache for binary operations (Ivan Levkivskyi, PR 19523)
- Cache types of type objects (Ivan Levkivskyi, PR 19514)
- Avoid duplicate work when checking boolean operations (Ivan Levkivskyi, PR 19515)
- Optimize generic inference passes (Ivan Levkivskyi, PR 19501)
- Speed up the default plugin (Jukka Lehtosalo, PRs 19385 and 19462)
- Remove nested imports from the default plugin (Ivan Levkivskyi, PR 19388)
- Micro‑optimize type expansion (Jukka Lehtosalo, PR 19461)
- Micro‑optimize type indirection (Jukka Lehtosalo, PR 19460)
- Micro‑optimize the plugin framework (Jukka Lehtosalo, PR 19464)
- Avoid temporary set creation in subtype checking (Jukka Lehtosalo, PR 19463)
- Subtype checking micro‑optimization (Jukka Lehtosalo, PR 19384)
- Return early where possible in subtype check (Stanislav Terliakov, PR 19400)
- Deduplicate some types before joining (Stanislav Terliakov, PR 19409)
- Speed up type checking by caching argument inference context (Jukka Lehtosalo, PR 19323)
- Optimize binding method self argument type and deprecation checks (Ivan Levkivskyi, PR 19556)
- Keep trivial instance types/aliases during expansion (Ivan Levkivskyi, PR 19543)
Fixed‑Format Cache (Experimental)
Mypy now supports a new cache format used for faster incremental builds. It makes incremental builds up to twice as fast. The feature is experimental and currently only supported when using a compiled version of mypy. Use --fixed-format-cache to enable the new format, or fixed_format_cache = True in a configuration file.
We plan to enable this by default in a future mypy release, and we'll eventually deprecate and remove support for the original JSON-based format.
Unlike the JSON-based cache format, the new binary format is currently not easy to parse and inspect by mypy users. We are planning to provide a tool to convert fixed-format cache files to JSON, but details of the output JSON may be different from the current JSON format. If you rely on being able to inspect mypy cache files, we recommend creating a GitHub issue and explaining your use case, so that we can more likely provide support for it. (Using MypyFile.read(binary_data) to inspect cache data may be sufficient to support some use cases.)
This feature was contributed by Ivan Levkivskyi (PR 19668, 19735, 19750, 19681, 19752, 19815).
Flexible Variable Definitions: Update
Mypy 1.16.0 introduced --allow-redefinition-new, which allows redefining variables with different types, and inferring union types for variables from multiple assignments. The feature is now documented in the --help output, but the feature is still experimental.
We are planning to enable this by default in mypy 2.0, and we will also deprecate the older --allow-redefinition flag. Since the new behavior differs significantly from the older flag, we encourage users of --allow-redefinition to experiment with --allow-redefinition-new and create a GitHub issue if the new functionality doesn't support some important use cases.
This feature was contributed by Jukka Lehtosalo.
Inferred Type for Bare ClassVar
A ClassVar without an explicit type annotation now causes the type of the variable to be inferred from the initializer:
from typing import ClassVar
class Item:
# Type of 'next_id' is now 'int' (it was 'Any')
next_id: ClassVar = 1
...
This feature was contributed by Ivan Levkivskyi (PR 19573).
Disjoint Base Classes (@disjoint_base, PEP 800)
Mypy now understands disjoint bases (PEP 800): it recognizes the @disjoint_base decorator, and rejects class definitions that combine mutually incompatible base classes, and takes advantage of the fact that such classes cannot exist in reachability and narrowing logic.
This class definition will now generate an error:
# Error: Class "Bad" has incompatible disjoint bases
class Bad(str, Exception):
...
This feature was contributed by Jelle Zijlstra (PR 19678).
Miscellaneous New Mypy Features
- Add --strict-equality-for-none to flag non-overlapping comparisons involving None (Christoph Tyralla, PR 19718)
- Don’t show import‑related errors after a module‑level assert such as assert sys.platform == "linux" that is always false (Stanislav Terliakov, PR 19347)
Improvements to Match Statements
- Add temporary named expressions for match subjects (Stanislav Terliakov, PR 18446)
- Fix unwrapping of assignment expressions in match subject (Marc Mueller, PR 19742)
- Omit errors for class patterns against object (Marc Mueller, PR 19709)
- Remove unnecessary error for certain match class patterns (Marc Mueller, PR 19708)
- Use union type for captured vars in or pattern (Marc Mueller, PR 19710)
- Prevent final reassignment inside match case (Omer Hadari, PR 19496)
Fixes to Crashes
- Fix crash with variadic tuple arguments to a generic type (Randolf Scholz, PR 19705)
- Fix crash when enable_error_code in pyproject.toml has wrong type (wyattscarpenter, PR 19494)
- Prevent crash for dataclass with PEP 695 TypeVarTuple on Python 3.13+ (Stanislav Terliakov, PR 19565)
- Fix crash on settable property alias (Ivan Levkivskyi, PR 19615)
Experimental Free-threading Support for Mypyc
All mypyc tests now pass on free-threading Python 3.14 release candidate builds. The performance of various micro-benchmarks scale well across multiple threads.
Free-threading support is still experimental. Note that native attribute access (get and set), list item access and certain other operations are still unsafe when there are race conditions. This will likely change in the future. You can follow the area-free-threading label in the mypyc issues tracker to follow progress.
Related PRs:
- Enable free‑threading when compiling multiple modules (Jukka Lehtosalo, PR 19541)
- Fix list.pop on free‑threaded builds (Jukka Lehtosalo, PR 19522)
- Make type objects immortal under free‑threading (Jukka Lehtosalo, PR 19538)
Mypyc: Support __new__
Mypyc now has rudimentary support for user-defined __new__ methods.
This feature was contributed by Piotr Sawicki (PR 19739).
Mypyc: Faster Generators and Async Functions
Generators and calls of async functions are now faster, sometimes by 2x or more.
Related PRs:
- Speed up for loops over native generators (Jukka Lehtosalo, PR 19415)
- Speed up native‑to‑native calls using await (Jukka Lehtosalo, PR 19398)
- Call generator helper directly in await expressions (Jukka Lehtosalo, PR 19376)
- Speed up generator allocation with per‑type freelists (Jukka Lehtosalo, PR 19316)
Miscellaneous Mypyc Improvements
- Special‑case certain Enum method calls for speed (Ivan Levkivskyi, PR 19634)
- Fix issues related to subclassing and undefined attribute tracking (Chainfire, PR 19787)
- Fix invalid C function signature (Jukka Lehtosalo, PR 19773)
- Speed up implicit __ne__ (Jukka Lehtosalo, PR 19759)
- Speed up equality with optional str/bytes types (Jukka Lehtosalo, PR 19758)
- Speed up access to empty tuples (BobTheBuidler, PR 19654)
- Speed up calls with *args (BobTheBuidler, PRs 19623 and 19631)
- Speed up calls with **kwargs (BobTheBuidler, PR 19630)
- Optimize type(x), x.__class__, and <type>.__name__ (Jukka Lehtosalo, PR 19691, 19683)
- Specialize bytes.decode for common encodings (Jukka Lehtosalo, PR 19688)
- Speed up in operations using final fixed‑length tuples (Jukka Lehtosalo, PR 19682)
- Optimize f‑string building from final values (BobTheBuidler, PR 19611)
- Add dictionary set item for exact dict instances (BobTheBuidler, PR 19657)
- Cache length when iterating over immutable types (BobTheBuidler, PR 19656)
- Fix name conflict related to attributes of generator classes (Piotr Sawicki, PR 19535)
- Fix segfault from heap type objects with a static docstring (Brian Schubert, PR 19636)
- Unwrap NewType to its base type for additional optimizations (BobTheBuidler, PR 19497)
- Generate an export table only for separate compilation (Jukka Lehtosalo, PR 19521)
- Speed up isinstance with built‑in types (Piotr Sawicki, PR 19435)
- Use native integers for some sequence indexing (Jukka Lehtosalo, PR 19426)
- Speed up isinstance(obj, list) (Piotr Sawicki, PR 19416)
- Report error on reserved method names (Piotr Sawicki, PR 19407)
- Speed up string equality (Jukka Lehtosalo, PR 19402)
- Raise NameError on undefined names (Piotr Sawicki, PR 19395)
- Use per‑type freelists for nested functions (Jukka Lehtosalo, PR 19390)
- Simplify comparison of tuple elements (Piotr Sawicki, PR 19396)
- Generate introspection signatures for compiled functions (Brian Schubert, PR 19307)
- Fix undefined attribute checking special case (Jukka Lehtosalo, PR 19378)
- Fix comparison of tuples with different lengths (Piotr Sawicki, PR 19372)
- Speed up list.clear (Jahongir Qurbonov, PR 19344)
- Speed up weakref.proxy (BobTheBuidler, PR 19217)
- Speed up weakref.ref (BobTheBuidler, PR 19099)
- Speed up str.count (BobTheBuidler, PR 19264)
Stubtest Improvements
- Add temporary --ignore-disjoint-bases flag to ease PEP 800 migration (Joren Hammudoglu, PR 19740)
- Flag redundant uses of @disjoint_base (Jelle Zijlstra, PR 19715)
- Improve signatures for __init__ of C extension classes (Stephen Morton, PR 18259)
- Handle overloads with mixed positional‑only parameters (Stephen Morton, PR 18287)
- Use “parameter” (not “argument”) in error messages (PrinceNaroliya, PR 19707)
- Don’t require @disjoint_base when __slots__ imply finality (Jelle Zijlstra, PR 19701)
- Allow runtime‑existing aliases of @type_check_only types (Brian Schubert, PR 19568)
- More detailed checking of type objects in stubtest (Stephen Morton, PR 18251)
- Support running stubtest in non-UTF8 terminals (Stanislav Terliakov, PR 19085)
Documentation Updates
- Add idlemypyextension to IDE integrations (CoolCat467, PR 18615)
- Document that object is often preferable to Any in APIs (wyattscarpenter, PR 19103)
- Include a detailed listing of flags enabled by --strict (wyattscarpenter, PR 19062)
- Update “common issues” (reveal_type/reveal_locals; note on orjson) (wyattscarpenter, PR 19059, 19058)
Other Notable Fixes and Improvements
- Remove deprecated --new-type-inference flag (the new algorithm has long been default) (Ivan Levkivskyi, PR 19570)
- Use empty context as a fallback for return expressions when outer context misleads inference (Ivan Levkivskyi, PR 19767)
- Fix forward references in type parameters of over‑parameterized PEP 695 aliases (Brian Schubert, PR 19725)
- Don’t expand PEP 695 aliases when checking node fullnames (Brian Schubert, PR 19699)
- Don’t use outer context for 'or' expression inference when LHS is Any (Stanislav Terliakov, PR 19748)
- Recognize buffer protocol special methods (Brian Schubert, PR 19581)
- Support attribute access on enum members correctly (Stanislav Terliakov, PR 19422)
- Check __slots__ assignments on self types (Stanislav Terliakov, PR 19332)
- Move self‑argument checks after decorator application (Stanislav Terliakov, PR 19490)
- Infer empty list for __slots__ and module __all__ (Stanislav Terliakov, PR 19348)
- Use normalized tuples for fallback calculation (Stanislav Terliakov, PR 19111)
- Preserve literals when joining similar types (Stanislav Terliakov, PR 19279)
- Allow adjacent conditionally‑defined overloads (Stanislav Terliakov, PR 19042)
- Check property decorators more strictly (Stanislav Terliakov, PR 19313)
- Support properties with generic setters (Ivan Levkivskyi, PR 19298)
- Generalize class/static method and property alias support (Ivan Levkivskyi, PR 19297)
- Re‑widen custom properties after narrowing (Ivan Levkivskyi, PR 19296)
- Avoid erasing type objects when checking runtime cover (Shantanu, PR 19320)
- Include tuple fallback in constraints built from tuple types (Stanislav Terliakov, PR 19100)
- Somewhat better isinstance support on old‑style unions (Shantanu, PR 19714)
- Improve promotions inside unions (Christoph Tyralla, PR 19245)
- Treat uninhabited types as having all attributes (Ivan Levkivskyi, PR 19300)
- Improve metaclass conflict checks (Robsdedude, PR 17682)
- Fixes to metaclass resolution algorithm (Robsdedude, PR 17713)
- PEP 702 @deprecated: handle “combined” overloads (Christoph Tyralla, PR 19626)
- PEP 702 @deprecated: include overloads in snapshot descriptions (Christoph Tyralla, PR 19613)
- Ignore overload implementation when checking __OP__ / __rOP__ compatibility (Stanislav Terliakov, PR 18502)
- Support _value_ as a fallback for ellipsis Enum members (Stanislav Terliakov, PR 19352)
- Sort arguments in TypedDict overlap messages (Marc Mueller, PR 19666)
- Fix handling of implicit return in lambda (Stanislav Terliakov, PR 19642)
- Improve behavior of uninhabited types (Stanislav Terliakov, PR 19648)
- Fix overload diagnostics when *args and **kwargs both match (Shantanu, PR 19614)
- Further fix overload diagnostics for *args/**kwargs (Shantanu, PR 19619)
- Show type variable name in "Cannot infer type argument" (Brian Schubert, PR 19290)
- Fail gracefully on unsupported template strings (PEP 750) (Brian Schubert, PR 19700)
- Revert colored argparse help for Python 3.14 (Marc Mueller, PR 19721)
- Update stubinfo for latest typeshed (Shantanu, PR 19771)
- Fix dict assignment when an incompatible same‑shape TypedDict exists (Stanislav Terliakov, PR 19592)
- Fix constructor type for subclasses of Any (Ivan Levkivskyi, PR 19295)
- Fix TypeGuard/TypeIs being forgotten in some cases (Brian Schubert, PR 19325)
- Fix TypeIs negative narrowing for unions of generics (Brian Schubert, PR 18193)
- dmypy suggest: Fix incorrect signature suggestion when a type matches a module name (Brian Schubert, PR 18937)
- dmypy suggest: Fix interaction with __new__ (Stanislav Terliakov, PR 18966)
- dmypy suggest: Support Callable / callable Protocols in decorator unwrapping (Anthony Sottile, PR 19072)
- Fix missing error when redeclaring a type variable in a nested generic class (Brian Schubert, PR 18883)
- Fix for overloaded type object erasure (Shantanu, PR 19338)
- Fix TypeGuard with call on temporary object (Saul Shanabrook, PR 19577)
Typeshed Updates
Please see git log for full list of standard library typeshed stub changes.
Acknowledgements
Thanks to all mypy contributors who contributed to this release:
- Ali Hamdan
- Anthony Sottile
- BobTheBuidler
- Brian Schubert
- Chainfire
- Charlie Denton
- Christoph Tyralla
- CoolCat467
- Daniel Hnyk
- Emily
- Emma Smith
- Ethan Sarp
- Ivan Levkivskyi
- Jahongir Qurbonov
- Jelle Zijlstra
- Joren Hammudoglu
- Jukka Lehtosalo
- Marc Mueller
- Omer Hadari
- Piotr Sawicki
- PrinceNaroliya
- Randolf Scholz
- Robsdedude
- Saul Shanabrook
- Shantanu
- Stanislav Terliakov
- Stephen Morton
- wyattscarpenter
I’d also like to thank my employer, Dropbox, for supporting mypy development.