First steps
Type system reference
Configuring and running mypy
Miscellaneous
Project Links
We’ve just uploaded mypy 1.19.0 to the Python Package Index (PyPI).Mypy is a static type checker for Python. This release includes new features, performanceimprovements and bug fixes. You can install it as follows:
python3 -m pip install -U mypy
You can read the full documentation for this release onRead the Docs.
Mypy uses a cache by default to speed up incremental runs by reusing partial resultsfrom earlier runs. Mypy 1.18 added a new binary fixed-format cache representation asan experimental feature. The feature is no longer experimental, and we are planningto enable it by default in a future mypy release (possibly 1.20), since it’s fasterand uses less space than the original, JSON-based cache format. Use--fixed-format-cache to enable the fixed-format cache.
Mypy now has an extra dependency on thelibrt PyPI package, as it’s needed forcache serialization and deserialization.
Mypy ships with a tool to convert fixed-format cache files to the old JSON format.Example of how to use this:
$ python -m mypy.exportjson .mypy_cache/.../my_module.data.ff
This way existing use cases that parse JSON cache files can be supported when usingthe new format, though an extra conversion step is needed.
This release includes these improvements:
Force-discard cache if cache format changed (Ivan Levkivskyi, PR20152)
Add tool to convert binary cache files to JSON (Jukka Lehtosalo, PR20071)
Use more efficient serialization format for long integers in cache files (Jukka Lehtosalo, PR20151)
More robust packing of floats in fixed-format cache (Ivan Levkivskyi, PR20150)
Use self-descriptive cache with type tags (Ivan Levkivskyi, PR20137)
Use fixed format for cache metas (Ivan Levkivskyi, PR20088)
Make metas more compact; fix indirect suppression (Ivan Levkivskyi, PR20075)
Use dedicated tags for most common cached instances (Ivan Levkivskyi, PR19762)
Mypy now recognizesTypeForm[T] as a type and implementsPEP 747. The feature is still experimental,and it’s disabled by default. Use--enable-incomplete-feature=TypeForm toenable type forms. A type form object captures the type information provided by aruntime type expression. Example:
fromtyping_extensionsimportTypeFormdeftrycast[T](typx:TypeForm[T],value:object)->T|None:...defexample(o:object)->None:# 'int | str' below is an expression that represents a type.# Unlike type[T], TypeForm[T] can be used with all kinds of types,# including union types.x=trycast(int|str,o)ifxisnotNone:# Type of 'x' is 'int | str' here...
This feature was contributed by David Foster (PR19596).
Do not push partial types to the binder (Stanislav Terliakov, PR20202)
Fix crash on recursive tuple with Hashable (Ivan Levkivskyi, PR20232)
Fix crash related to decorated functions (Stanislav Terliakov, PR20203)
Do not abort constructing TypeAlias if only type parameters hold us back (Stanislav Terliakov, PR20162)
Use the fallback forModuleSpec early if it can never be resolved (Stanislav Terliakov, PR20167)
Do not store deferred NamedTuple fields as redefinitions (Stanislav Terliakov, PR20147)
Discard partial types remaining after inference failure (Stanislav Terliakov, PR20126)
Fix an infinite recursion bug (Stanislav Terliakov, PR20127)
Fix IsADirectoryError for namespace packages when using –linecoverage-report (wyattscarpenter, PR20109)
Fix an internal error when creating cobertura output for namespace package (wyattscarpenter, PR20112)
Allow type parameters reusing the name missing from current module (Stanislav Terliakov, PR20081)
Prevent TypeGuardedType leak from narrowing declared type as part of type variable bound (Stanislav Terliakov, PR20046)
Fix crash on invalid unpack in base class (Ivan Levkivskyi, PR19962)
Traverse ParamSpec prefix where we should (Ivan Levkivskyi, PR19800)
Fix daemon crash related to imports (Ivan Levkivskyi, PR20271)
__getattr__,__setattr__, and__delattr__¶Mypyc now has partial support for__getattr__,__setattr__ and__delattr__ methods in native classes.
Note that native attributes are not stored using__dict__. Setting attributesdirectly while bypassing__setattr__ is possible by usingsuper().__setattr__(...) orobject.__setattr__(...), but not via__dict__.
Example:
classDemo:_data:dict[str,str]def__init__(self)->None:# Initialize data dict without calling our __setattr__super().__setattr__("_data",{})def__setattr__(self,name:str,value:str)->None:print(f"Setting{name} ={value!r}")ifname=="_data":raiseAttributeError("'_data' cannot be set")self._data[name]=valuedef__getattr__(self,name:str)->str:print(f"Getting{name}")try:returnself._data[name]exceptKeyError:raiseAttributeError(name)d=Demo()d.x="hello"d.y="world"print(d.x)print(d.y)
Related PRs:
Fix__new__ in native classes with inheritance (Piotr Sawicki, PR20302)
Fix crash onsuper in generator (Ivan Levkivskyi, PR20291)
Fix calling base class async method usingsuper() (Jukka Lehtosalo, PR20254)
Fix async or generator methods in traits (Jukka Lehtosalo, PR20246)
Optimize equality check with string literals (BobTheBuidler, PR19883)
Fix inheritance of async defs (Jukka Lehtosalo, PR20044)
Reject invalidmypyc_attr args (BobTheBuidler, PR19963)
Optimizeisinstance with tuple of primitive types (BobTheBuidler, PR19949)
Optimize away first index check in for loops if length > 1 (BobTheBuidler, PR19933)
Fix broken exception/cancellation handling in async def (Jukka Lehtosalo, PR19951)
Transformobject.__new__ inside__new__ (Piotr Sawicki, PR19866)
Fix crash with NewType and other non-class types in incremental builds (Jukka Lehtosalo, PR19837)
Optimize container creation from expressions with length known at compile time (BobTheBuidler, PR19503)
Allow per-class free list to be used with inheritance (Jukka Lehtosalo, PR19790)
Fix object finalization (Marc Mueller, PR19749)
Allow defining a single-item free “list” for a native class (Jukka Lehtosalo, PR19785)
Speed up unary “not” (Jukka Lehtosalo, PR19774)
Update duck type compatibility: mention strict-bytes and mypy 2.0 (wyattscarpenter, PR20121)
Document--enable-incomplete-featureTypeForm (wyattscarpenter, PR20173)
Change the inline TypedDict example (wyattscarpenter, PR20172)
ReplaceList with built‑inlist (PEP 585) (Thiago J. Barbalho, PR20000)
Improve junit documentation (wyattscarpenter, PR19867)
Fix annotated with function as type keyword list parameter (KarelKenens, PR20094)
Fix errors for raise NotImplemented (Shantanu, PR20168)
Don’t let help formatter line-wrap URLs (Frank Dana, PR19825)
Do not cache fast container types inside lambdas (Stanislav Terliakov, PR20166)
Respect force-union-syntax flag in error hint (Marc Mueller, PR20165)
Fix type checking of dict type aliases (Shantanu, PR20170)
Use pretty callable formatting more often for callable expressions (Theodore Ando, PR20128)
Use dummy concrete type instead ofAny when checking protocol variance (bzoracler, PR20110)
PEP 696: Fix swapping TypeVars with defaults (Randolf Scholz, PR19449)
Fix narrowing of class pattern with union type (Randolf Scholz, PR19517)
Do not emit unreachable warnings for lines that returnNotImplemented (Christoph Tyralla, PR20083)
Fix matching againsttyping.Callable andProtocol types (Randolf Scholz, PR19471)
Make--pretty work better on multi-line issues (A5rocks, PR20056)
More precise return types forTypedDict.get (Randolf Scholz, PR19897)
Prevent false unreachable warnings for@final instances that occur when strict optional checking is disabled (Christoph Tyralla, PR20045)
Check class references to catch non-existent classes in match cases (A5rocks, PR20042)
Do not sort unused error codes in unused error codes warning (wyattscarpenter, PR20036)
Fix[name-defined] false positive inclassA[X,Y=X]: case (sobolevn, PR20021)
Filter SyntaxWarnings during AST parsing (Marc Mueller, PR20023)
Make untyped decorator its own error code (wyattscarpenter, PR19911)
Support error codes from plugins in options (Sigve Sebastian Farstad, PR19719)
Allow returning Literals in__new__ (James Hilton-Balfe, PR15687)
Inverse interface freshness logic (Ivan Levkivskyi, PR19809)
Do not report exhaustive-match after deferral (Stanislav Terliakov, PR19804)
Makeuntyped_calls_exclude invalidate cache (Ivan Levkivskyi, PR19801)
Add await to empty context hack (Stanislav Terliakov, PR19777)
Consider non-empty enums assignable to Self (Stanislav Terliakov, PR19779)
Please seegit log for full list of standard library typeshed stub changes.
Fix noncommutative joins with bounded TypeVars (Shantanu, PR20345)
Respect output format for cached runs by serializing raw errors in cache metas (Ivan Levkivskyi, PR20372)
Allowtypes.NoneType in match cases (A5rocks, PR20383)
Fix mypyc generator regression with empty tuple (BobTheBuidler, PR20371)
Fix crash involving Unpack-ed TypeVarTuple (Shantanu, PR20323)
Fix crash on star import of redefinition (Ivan Levkivskyi, PR20333)
Fix crash on typevar with forward ref used in other module (Ivan Levkivskyi, PR20334)
Fail with an explicit error on PyPy (Ivan Levkivskyi, PR20389)
Thanks to all mypy contributors who contributed to this release:
A5rocks
BobTheBuidler
bzoracler
Chainfire
Christoph Tyralla
David Foster
Frank Dana
Guo Ci
iap
Ivan Levkivskyi
James Hilton-Balfe
jhance
Joren Hammudoglu
Jukka Lehtosalo
KarelKenens
Kevin Kannammalil
Marc Mueller
Michael Carlstrom
Michael J. Sullivan
Piotr Sawicki
Randolf Scholz
Shantanu
Sigve Sebastian Farstad
sobolevn
Stanislav Terliakov
Stephen Morton
Theodore Ando
Thiago J. Barbalho
wyattscarpenter
I’d also like to thank my employer, Dropbox, for supporting mypy development.
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, performanceimprovements and bug fixes. You can install it as follows:
python3 -m pip install -U mypy
You can read the full documentation for this release onRead the Docs.
Mypy 1.18.1 includes numerous performance improvements, resulting in about 40% speedupcompared to 1.17 when type checking mypy itself. In extreme cases, the improvementcan 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. Whenreporting issues with unexpected inferred types, please also check if--disable-expression-cache will work around the issue, as it turns off some ofthese optimizations.
Improve self check performance by 1.8% (Jukka Lehtosalo, PR19768,19769,19770)
Optimize fixed-format deserialization (Ivan Levkivskyi, PR19765)
Use macros to optimize fixed-format deserialization (Ivan Levkivskyi, PR19757)
Two additional micro‑optimizations (Ivan Levkivskyi, PR19627)
Another set of micro‑optimizations (Ivan Levkivskyi, PR19633)
Cache common types (Ivan Levkivskyi, PR19621)
Skip more method bodies in third‑party libraries for speed (Ivan Levkivskyi, PR19586)
Simplify the representation of callable types (Ivan Levkivskyi, PR19580)
Add cache for types of some expressions (Ivan Levkivskyi, PR19505)
Use cache for dictionary expressions (Ivan Levkivskyi, PR19536)
Use cache for binary operations (Ivan Levkivskyi, PR19523)
Cache types of type objects (Ivan Levkivskyi, PR19514)
Avoid duplicate work when checking boolean operations (Ivan Levkivskyi, PR19515)
Optimize generic inference passes (Ivan Levkivskyi, PR19501)
Speed up the default plugin (Jukka Lehtosalo, PRs19385 and19462)
Remove nested imports from the default plugin (Ivan Levkivskyi, PR19388)
Micro‑optimize type expansion (Jukka Lehtosalo, PR19461)
Micro‑optimize type indirection (Jukka Lehtosalo, PR19460)
Micro‑optimize the plugin framework (Jukka Lehtosalo, PR19464)
Avoid temporary set creation in subtype checking (Jukka Lehtosalo, PR19463)
Subtype checking micro‑optimization (Jukka Lehtosalo, PR19384)
Return early where possible in subtype check (Stanislav Terliakov, PR19400)
Deduplicate some types before joining (Stanislav Terliakov, PR19409)
Speed up type checking by caching argument inference context (Jukka Lehtosalo, PR19323)
Optimize binding method self argument type and deprecation checks (Ivan Levkivskyi, PR19556)
Keep trivial instance types/aliases during expansion (Ivan Levkivskyi, PR19543)
Mypy now supports a new cache format used for faster incremental builds. It makesincremental builds up to twice as fast. The feature is experimental andcurrently only supported when using a compiled version of mypy. Use--fixed-format-cacheto enable the new format, orfixed_format_cache=True in a configuration file.
We plan to enable this by default in a future mypy release, and we’ll eventuallydeprecate and remove support for the original JSON-based format.
Unlike the JSON-based cache format, the new binary format is currentlynot easy to parse and inspect by mypy users. We are planning to provide a tool toconvert fixed-format cache files to JSON, but details of the output JSON may bedifferent from the current JSON format. If you rely on being able to inspectmypy cache files, we recommend creating a GitHub issue and explaining your usecase, so that we can more likely provide support for it. (UsingMypyFile.read(binary_data) to inspect cache data may be sufficient to supportsome use cases.)
This feature was contributed by Ivan Levkivskyi (PR19668,19735,19750,19681,19752,19815).
Mypy 1.16.0 introduced--allow-redefinition-new, which allows redefining variableswith 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 theolder--allow-redefinition flag. Since the new behavior differs significantly fromthe older flag, we encourage users of--allow-redefinition to experiment with--allow-redefinition-new and create a GitHub issue if the new functionality doesn’tsupport some important use cases.
This feature was contributed by Jukka Lehtosalo.
A ClassVar without an explicit type annotation now causes the type of the variableto be inferred from the initializer:
fromtypingimportClassVarclassItem:# Type of 'next_id' is now 'int' (it was 'Any')next_id:ClassVar=1...
This feature was contributed by Ivan Levkivskyi (PR19573).
Mypy now understands disjoint bases (PEP 800): it recognizes the@disjoint_basedecorator, and rejects class definitions that combine mutually incompatible base classes,and takes advantage of the fact that such classes cannot exist in reachability andnarrowing logic.
This class definition will now generate an error:
# Error: Class "Bad" has incompatible disjoint basesclassBad(str,Exception):...
This feature was contributed by Jelle Zijlstra (PR19678).
Add temporary named expressions for match subjects (Stanislav Terliakov, PR18446)
Fix unwrapping of assignment expressions in match subject (Marc Mueller, PR19742)
Omit errors for class patterns against object (Marc Mueller, PR19709)
Remove unnecessary error for certain match class patterns (Marc Mueller, PR19708)
Use union type for captured vars in or pattern (Marc Mueller, PR19710)
Prevent final reassignment inside match case (Omer Hadari, PR19496)
Fix crash with variadic tuple arguments to a generic type (Randolf Scholz, PR19705)
Fix crash when enable_error_code in pyproject.toml has wrong type (wyattscarpenter, PR19494)
Prevent crash for dataclass with PEP 695 TypeVarTuple on Python 3.13+ (Stanislav Terliakov, PR19565)
Fix crash on settable property alias (Ivan Levkivskyi, PR19615)
All mypyc tests now pass on free-threading Python 3.14 release candidate builds. The performanceof 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 stillunsafe when there are race conditions. This will likely change in the future.You can follow thearea-free-threading labelin the mypyc issues tracker to follow progress.
Related PRs:
__new__¶Mypyc now has rudimentary support for user-defined__new__ methods.
This feature was contributed by Piotr Sawicki (PR19739).
Generators and calls of async functions are now faster, sometimes by 2x or more.
Related PRs:
Special‑case certain Enum method calls for speed (Ivan Levkivskyi, PR19634)
Fix issues related to subclassing and undefined attribute tracking (Chainfire, PR19787)
Fix invalid C function signature (Jukka Lehtosalo, PR19773)
Speed up implicit__ne__ (Jukka Lehtosalo, PR19759)
Speed up equality with optional str/bytes types (Jukka Lehtosalo, PR19758)
Speed up access to empty tuples (BobTheBuidler, PR19654)
Speed up calls with**kwargs (BobTheBuidler, PR19630)
Optimizetype(x),x.__class__, and<type>.__name__ (Jukka Lehtosalo, PR19691,19683)
Specializebytes.decode for common encodings (Jukka Lehtosalo, PR19688)
Speed upin operations using final fixed‑length tuples (Jukka Lehtosalo, PR19682)
Optimize f‑string building from final values (BobTheBuidler, PR19611)
Add dictionary set item for exact dict instances (BobTheBuidler, PR19657)
Cache length when iterating over immutable types (BobTheBuidler, PR19656)
Fix name conflict related to attributes of generator classes (Piotr Sawicki, PR19535)
Fix segfault from heap type objects with a static docstring (Brian Schubert, PR19636)
Unwrap NewType to its base type for additional optimizations (BobTheBuidler, PR19497)
Generate an export table only for separate compilation (Jukka Lehtosalo, PR19521)
Speed upisinstance with built‑in types (Piotr Sawicki, PR19435)
Use native integers for some sequence indexing (Jukka Lehtosalo, PR19426)
Speed upisinstance(obj,list) (Piotr Sawicki, PR19416)
Report error on reserved method names (Piotr Sawicki, PR19407)
Speed up string equality (Jukka Lehtosalo, PR19402)
RaiseNameError on undefined names (Piotr Sawicki, PR19395)
Use per‑type freelists for nested functions (Jukka Lehtosalo, PR19390)
Simplify comparison of tuple elements (Piotr Sawicki, PR19396)
Generate introspection signatures for compiled functions (Brian Schubert, PR19307)
Fix undefined attribute checking special case (Jukka Lehtosalo, PR19378)
Fix comparison of tuples with different lengths (Piotr Sawicki, PR19372)
Speed uplist.clear (Jahongir Qurbonov, PR19344)
Speed upweakref.proxy (BobTheBuidler, PR19217)
Speed upweakref.ref (BobTheBuidler, PR19099)
Speed upstr.count (BobTheBuidler, PR19264)
Add temporary--ignore-disjoint-bases flag to ease PEP 800 migration (Joren Hammudoglu, PR19740)
Flag redundant uses of@disjoint_base (Jelle Zijlstra, PR19715)
Improve signatures for__init__ of C extension classes (Stephen Morton, PR18259)
Handle overloads with mixed positional‑only parameters (Stephen Morton, PR18287)
Use “parameter” (not “argument”) in error messages (PrinceNaroliya, PR19707)
Don’t require@disjoint_base when__slots__ imply finality (Jelle Zijlstra, PR19701)
Allow runtime‑existing aliases of@type_check_only types (Brian Schubert, PR19568)
More detailed checking of type objects in stubtest (Stephen Morton, PR18251)
Support running stubtest in non-UTF8 terminals (Stanislav Terliakov, PR19085)
Add idlemypyextension to IDE integrations (CoolCat467, PR18615)
Document thatobject is often preferable toAny in APIs (wyattscarpenter, PR19103)
Include a detailed listing of flags enabled by--strict (wyattscarpenter, PR19062)
Update “common issues” (reveal_type/reveal_locals; note on orjson) (wyattscarpenter, PR19059,19058)
Remove deprecated--new-type-inference flag (the new algorithm has long been default) (Ivan Levkivskyi, PR19570)
Use empty context as a fallback for return expressions when outer context misleads inference (Ivan Levkivskyi, PR19767)
Fix forward references in type parameters of over‑parameterized PEP 695 aliases (Brian Schubert, PR19725)
Don’t expand PEP 695 aliases when checking node fullnames (Brian Schubert, PR19699)
Don’t use outer context for ‘or’ expression inference when LHS is Any (Stanislav Terliakov, PR19748)
Recognize buffer protocol special methods (Brian Schubert, PR19581)
Support attribute access on enum members correctly (Stanislav Terliakov, PR19422)
Check__slots__ assignments on self types (Stanislav Terliakov, PR19332)
Move self‑argument checks after decorator application (Stanislav Terliakov, PR19490)
Infer empty list for__slots__ and module__all__ (Stanislav Terliakov, PR19348)
Use normalized tuples for fallback calculation (Stanislav Terliakov, PR19111)
Preserve literals when joining similar types (Stanislav Terliakov, PR19279)
Allow adjacent conditionally‑defined overloads (Stanislav Terliakov, PR19042)
Check property decorators more strictly (Stanislav Terliakov, PR19313)
Support properties with generic setters (Ivan Levkivskyi, PR19298)
Generalize class/static method and property alias support (Ivan Levkivskyi, PR19297)
Re‑widen custom properties after narrowing (Ivan Levkivskyi, PR19296)
Avoid erasing type objects when checking runtime cover (Shantanu, PR19320)
Include tuple fallback in constraints built from tuple types (Stanislav Terliakov, PR19100)
Somewhat better isinstance support on old‑style unions (Shantanu, PR19714)
Improve promotions inside unions (Christoph Tyralla, PR19245)
Treat uninhabited types as having all attributes (Ivan Levkivskyi, PR19300)
Improve metaclass conflict checks (Robsdedude, PR17682)
Fixes to metaclass resolution algorithm (Robsdedude, PR17713)
PEP 702 @deprecated: handle “combined” overloads (Christoph Tyralla, PR19626)
PEP 702 @deprecated: include overloads in snapshot descriptions (Christoph Tyralla, PR19613)
Ignore overload implementation when checking__OP__ /__rOP__ compatibility (Stanislav Terliakov, PR18502)
Support_value_ as a fallback for ellipsis Enum members (Stanislav Terliakov, PR19352)
Sort arguments in TypedDict overlap messages (Marc Mueller, PR19666)
Fix handling of implicit return in lambda (Stanislav Terliakov, PR19642)
Improve behavior of uninhabited types (Stanislav Terliakov, PR19648)
Fix overload diagnostics when*args and**kwargs both match (Shantanu, PR19614)
Further fix overload diagnostics for*args/**kwargs (Shantanu, PR19619)
Show type variable name in “Cannot infer type argument” (Brian Schubert, PR19290)
Fail gracefully on unsupported template strings (PEP 750) (Brian Schubert, PR19700)
Revert colored argparse help for Python 3.14 (Marc Mueller, PR19721)
Update stubinfo for latest typeshed (Shantanu, PR19771)
Fix dict assignment when an incompatible same‑shape TypedDict exists (Stanislav Terliakov, PR19592)
Fix constructor type for subclasses of Any (Ivan Levkivskyi, PR19295)
Fix TypeGuard/TypeIs being forgotten in some cases (Brian Schubert, PR19325)
Fix TypeIs negative narrowing for unions of generics (Brian Schubert, PR18193)
dmypy suggest: Fix incorrect signature suggestion when a type matches a module name (Brian Schubert, PR18937)
dmypy suggest: Fix interaction with__new__ (Stanislav Terliakov, PR18966)
dmypy suggest: Support Callable / callable Protocols in decorator unwrapping (Anthony Sottile, PR19072)
Fix missing error when redeclaring a type variable in a nested generic class (Brian Schubert, PR18883)
Fix for overloaded type object erasure (Shantanu, PR19338)
Fix TypeGuard with call on temporary object (Saul Shanabrook, PR19577)
Please seegit log for full list of standard library typeshed stub changes.
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.
We’ve just uploaded mypy 1.17 to the Python Package Index (PyPI).Mypy is a static type checker for Python. This release includes new features and bug fixes.You can install it as follows:
python3 -m pip install -U mypy
You can read the full documentation for this release onRead the Docs.
Mypy can now optionally generate an error if a match statement does notmatch exhaustively, without having to useassert_never(...). Enablethis by using--enable-error-codeexhaustive-match.
Example:
# mypy: enable-error-code=exhaustive-matchimportenumclassColor(enum.Enum):RED=1BLUE=2defshow_color(val:Color)->None:# error: Unhandled case for values of type "Literal[Color.BLUE]"matchval:caseColor.RED:print("red")
This feature was contributed by Donal Burns (PR19144).
This release includes additional improvements to how attribute typesand kinds are resolved. These fix many bugs and overall improve consistency.
Handle corner case: protocol/class variable/descriptor (Ivan Levkivskyi, PR19277)
Fix a few inconsistencies in protocol/type object interactions (Ivan Levkivskyi, PR19267)
Refactor/unify access to static attributes (Ivan Levkivskyi, PR19254)
Remove inconsistencies in operator handling (Ivan Levkivskyi, PR19250)
Make protocol subtyping more consistent (Ivan Levkivskyi, PR18943)
Previous mypy versions could infer different types for certain expressionsacross different runs (typically depending on which order certain typeswere processed, and this order was nondeterministic). This release includesfixes to several such issues.
Fix nondeterministic type checking by making join with explicit Protocol and type promotion commute (Shantanu, PR18402)
Fix nondeterministic type checking caused by nonassociative of None joins (Shantanu, PR19158)
Fix nondeterministic type checking caused by nonassociativity of joins (Shantanu, PR19147)
Fix nondeterministic type checking by making join betweentype and TypeVar commute (Shantanu, PR19149)
Mypy now requires--python-version3.9 or greater. Support for targeting Python 3.8 isfully removed now. Since 3.8 is an unsupported version, mypy will default to the oldestsupported version (currently 3.9) if you still try to target 3.8.
This change is necessary because typeshed stopped supporting Python 3.8 after itreached its End of Life in October 2024.
Mypy is now tested on 3.14 and mypyc works with 3.14.0b3 and later.Binary wheels compiled with mypyc for mypy itself will be available for 3.14some time after 3.14.0rc1 has been released.
Note that not all features are supported just yet.
Contributed by Marc Mueller (PR19164)
--force-uppercase-builtins¶Mypy only supports Python 3.9+. The--force-uppercase-builtins flag is nowdeprecated as unnecessary, and a no-op. It will be removed in a future version.
Contributed by Marc Mueller (PR19176)
This release includes both performance improvements and bug fixes relatedto generators and async functions (these share many implementation details).
Fix exception swallowing in async try/finally blocks with await (Chainfire, PR19353)
Fix AttributeError in async try/finally with mixed return paths (Chainfire, PR19361)
Make generated generator helper method internal (Jukka Lehtosalo, PR19268)
Free coroutine after await encounters StopIteration (Jukka Lehtosalo, PR19231)
Use non-tagged integer for generator label (Jukka Lehtosalo, PR19218)
Merge generator and environment classes in simple cases (Jukka Lehtosalo, PR19207)
Mypyc has minimal, quite memory-unsafe support for the free threadedbuilds of 3.14. It is also only lightly tested. Bug reports and experiencereports are welcome!
Here are some of the major limitations:
Free threading only works when compiling a single module at a time.
If there is concurrent access to an object while another thread is mutating the sameobject, it’s possible to encounter segfaults and memory corruption.
There are no efficient native primitives for thread synthronization, though theregularthreading module can be used.
Some workloads don’t scale well to multiple threads for no clear reason.
Related PRs:
Derive .c file name from full module name if using multi_file (Jukka Lehtosalo, PR19278)
Support overriding the group name used in output files (Jukka Lehtosalo, PR19272)
Add note about using non-native class to subclass built-in types (Jukka Lehtosalo, PR19236)
Make some generated classes implicitly final (Jukka Lehtosalo, PR19235)
Don’t simplify module prefixes if using separate compilation (Jukka Lehtosalo, PR19206)
Add import fortypes in__exit__ method signature (Alexey Makridenko, PR19120)
Add support for including class and property docstrings (Chad Dombrova, PR17964)
Don’t generateIncomplete|None=None argument annotation (Sebastian Rittau, PR19097)
Support several more constructs in stubgen’s alias printer (Stanislav Terliakov, PR18888)
Combine the revealed types of multiple iteration steps in a more robust manner (Christoph Tyralla, PR19324)
Improve the handling of “iteration dependent” errors and notes in finally clauses (Christoph Tyralla, PR19270)
Lessen dmypy suggest path limitations for Windows machines (CoolCat467, PR19337)
Fix type ignore comments erroneously marked as unused by dmypy (Charlie Denton, PR15043)
Fix misspelledexhaustive-match error code (johnthagen, PR19276)
Fix missing error context for unpacking assignment involving star expression (Brian Schubert, PR19258)
Fix and simplify error de-duplication (Ivan Levkivskyi, PR19247)
DisallowClassVar in type aliases (Brian Schubert, PR19263)
Add script that prints list of compiled files when compiling mypy (Jukka Lehtosalo, PR19260)
Fix help message url for “None and Optional handling” section (Guy Wilson, PR19252)
Display fully qualified name of imported base classes in errors about incompatible overrides (Mikhail Golubev, PR19115)
Avoid falseunreachable,redundant-expr, andredundant-casts warnings in loops more robustly and efficiently, and avoid multiplerevealedtype notes for the same line (Christoph Tyralla, PR19118)
Fix type extraction fromisinstance checks (Stanislav Terliakov, PR19223)
Erase stray type variables infunctools.partial (Stanislav Terliakov, PR18954)
Make inferring condition value recognize the whole truth table (Stanislav Terliakov, PR18944)
Support type aliases,NamedTuple andTypedDict in constrained TypeVar defaults (Stanislav Terliakov, PR18884)
Move dataclasskw_only fields to the end of the signature (Stanislav Terliakov, PR19018)
Provide a better fallback value for thepython_version option (Marc Mueller, PR19162)
Avoid spurious non-overlapping equality error with metaclass with__eq__ (Michael J. Sullivan, PR19220)
Narrow type variable bounds (Ivan Levkivskyi, PR19183)
Add classifier for Python 3.14 (Marc Mueller, PR19199)
Capitalize syntax error messages (Charulata, PR19114)
Infer constraints eagerly if actual is Any (Ivan Levkivskyi, PR19190)
Include walrus assignments in conditional inference (Stanislav Terliakov, PR19038)
Use PEP 604 syntax when converting types to strings (Marc Mueller, PR19179)
Use more lower-case builtin types in error messages (Marc Mueller, PR19177)
Fix example to use correct method of Stack (Łukasz Kwieciński, PR19123)
Forbid.pop ofReadonlyNotRequired TypedDict items (Stanislav Terliakov, PR19133)
Emit a friendlier warning on invalid exclude regex, instead of a stacktrace (wyattscarpenter, PR19102)
Enable ANSI color codes for dmypy client in Windows (wyattscarpenter, PR19088)
Extend special case for context-based type variable inference to unions in return position (Stanislav Terliakov, PR18976)
Thanks to all mypy contributors who contributed to this release:
Alexey Makridenko
Brian Schubert
Chad Dombrova
Chainfire
Charlie Denton
Charulata
Christoph Tyralla
CoolCat467
Donal Burns
Guy Wilson
Ivan Levkivskyi
johnthagen
Jukka Lehtosalo
Łukasz Kwieciński
Marc Mueller
Michael J. Sullivan
Mikhail Golubev
Sebastian Rittau
Shantanu
Stanislav Terliakov
wyattscarpenter
I’d also like to thank my employer, Dropbox, for supporting mypy development.
We’ve just uploaded mypy 1.16 to the Python Package Index (PyPI).Mypy is a static type checker for Python. This release includes new features and bug fixes.You can install it as follows:
python3 -m pip install -U mypy
You can read the full documentation for this release onRead the Docs.
Mypy now supports using different types for a property getter and setter:
classA:_value:int@propertydeffoo(self)->int:returnself._value@foo.setterdeffoo(self,x:str|int)->None:try:self._value=int(x)exceptValueError:raiseException(f"'{x}' is not a valid value for 'foo'")
This was contributed by Ivan Levkivskyi (PR18510).
Mypy now allows unannotated variables to be freely redefined withdifferent types when using the experimental--allow-redefinition-newflag. You will also need to enable--local-partial-types. Mypy willnow infer a union type when different types are assigned to avariable:
# mypy: allow-redefinition-new, local-partial-typesdeff(n:int,b:bool)->int|str:ifb:x=nelse:x=str(n)# Type of 'x' is int | str here.returnx
Without the new flag, mypy only supports inferring optional types (X|None) from multiple assignments, but now mypy can infer arbitraryunion types.
An unannotated variable can now also have different types in differentcode locations:
# mypy: allow-redefinition-new, local-partial-types...ifcond():forxinrange(n):# Type of 'x' is 'int' here...else:forxin['a','b']:# Type of 'x' is 'str' here...
We are planning to turn this flag on by default in mypy 2.0, alongwith--local-partial-types. The feature is still experimental andhas known issues, and the semantics may still change in thefuture. You may need to update or add type annotations when switchingto the new behavior, but if you encounter anything unexpected, pleasecreate a GitHub issue.
Mypy can now detect additional errors in code that usesAny types or has missing function annotations.
When callingdict.get(x,None) on an object of typedict[str,Any], thisnow results in an optional type (in the past it wasAny):
deff(d:dict[str,Any])->int:# Error: Return value has type "Any | None" but expected "int"returnd.get("x",None)
Type narrowing using assignments can result in more precise types inthe presence ofAny types:
deffoo():...defbar(n:int)->None:x=foo()# Type of 'x' is 'Any' hereifn>5:x=str(n)# Type of 'x' is 'str' here
When using--check-untyped-defs, unannotated overrides are nowchecked more strictly against superclass definitions.
Related PRs:
This release includes several fixes to inconsistent resolution of attribute, method and descriptor types.
Consolidate descriptor handling (Ivan Levkivskyi, PR18831)
Make multiple inheritance checking use common semantics (Ivan Levkivskyi, PR18876)
Make method override checking use common semantics (Ivan Levkivskyi, PR18870)
Fix descriptor overload selection (Ivan Levkivskyi, PR18868)
Handle union types when bindingself (Ivan Levkivskyi, PR18867)
Make variable override checking use common semantics (Ivan Levkivskyi, PR18847)
Make descriptor handling behave consistently (Ivan Levkivskyi, PR18831)
The implementation can now be omitted for abstract overloaded methods,even outside stubs:
fromabcimportabstractmethodfromtypingimportoverloadclassC:@abstractmethod@overloaddeffoo(self,x:int)->int:...@abstractmethod@overloaddeffoo(self,x:str)->str:...# No implementation required for "foo"
This was contributed by Ivan Levkivskyi (PR18882).
You can now use--exclude-gitignore to exclude everything in a.gitignore file from the mypy build. This behaves similar toexcluding the paths using--exclude. We might enable this by defaultin a future mypy release.
This was contributed by Ivan Levkivskyi (PR18696).
It’s now possible to selectively disable warnings generated fromwarnings.deprecatedusing the--deprecated-calls-excludeoption:
# mypy --enable-error-code deprecated# --deprecated-calls-exclude=foo.Aimportfoofoo.A().func()# OK, the deprecated warning is ignored
# file foo.pyfromtyping_extensionsimportdeprecatedclassA:@deprecated("Use A.func2 instead")deffunc(self):pass...
Contributed by Marc Mueller (PR18641)
You can now declare a class as a non-native class when compiling withmypyc. Unlike native classes, which are extension classes and have animmutable structure, non-native classes are normal Python classes atruntime and are fully dynamic. Example:
frommypy_extensionsimportmypyc_attr@mypyc_attr(native_class=False)classNonNativeClass:...o=NonNativeClass()# Ok, even if attribute "foo" not declared in class bodysetattr(o,"foo",1)
Classes are native by default in compiled modules, but classes thatuse certain features (such as most metaclasses) are implicitlynon-native.
You can also explicitly declare a class as native. In this case mypycwill generate an error if it can’t compile the class as a nativeclass, instead of falling back to a non-native class:
frommypy_extensionsimportmypyc_attrfromfooimportMyMeta# Error: Unsupported metaclass for a native class@mypyc_attr(native_class=True)classC(metaclass=MyMeta):...
Since native classes are significantly more efficient that non-nativeclasses, you may want to ensure that certain classes always compiledas native classes.
This feature was contributed by Valentin Stanciu (PR18802).
Improve documentation of native and non-native classes (Jukka Lehtosalo, PR19154)
Fix compilation when using Python 3.13 debug build (Valentin Stanciu, PR19045)
Show the reason why a class can’t be a native class (Valentin Stanciu, PR19016)
Support await/yield while temporary values are live (Michael J. Sullivan, PR16305)
Fix spilling values with overlapping error values (Jukka Lehtosalo, PR18961)
Fix reference count of spilled register in async def (Jukka Lehtosalo, PR18957)
Add basic optimization forsorted (Marc Mueller, PR18902)
Fix access of class object in a type annotation (Advait Dixit, PR18874)
Optimizelist.__imul__ andtuple.__mul__(Marc Mueller, PR18887)
Optimizelist.__add__,list.__iadd__ andtuple.__add__ (Marc Mueller, PR18845)
Add and implement primitivelist.copy() (exertustfm, PR18771)
Optimizebuiltins.repr (Marc Mueller, PR18844)
Support iterating over keys/values/items of dict-bound TypeVar and ParamSpec.kwargs (Stanislav Terliakov, PR18789)
Add efficient primitives forstr.strip() etc. (Advait Dixit, PR18742)
Document thatstrip() etc. are optimized (Jukka Lehtosalo, PR18793)
Fix mypyc crash with enum type aliases (Valentin Stanciu, PR18725)
Optimizestr.find andstr.rfind (Marc Mueller, PR18709)
Optimizestr.__contains__ (Marc Mueller, PR18705)
Fix order of steal/unborrow in tuple unpacking (Ivan Levkivskyi, PR18732)
Optimizestr.partition andstr.rpartition (Marc Mueller, PR18702)
Optimizestr.startswith andstr.endswith with tuple argument (Marc Mueller, PR18678)
Improvestr.startswith andstr.endswith with tuple argument (Marc Mueller, PR18703)
pythoncapi_compat: don’t define Py_NULL if it is already defined (Michael R. Crusoe, PR18699)
Optimizestr.splitlines (Marc Mueller, PR18677)
Markdict.setdefault as optimized (Marc Mueller, PR18685)
Support__del__ methods (Advait Dixit, PR18519)
Optimizestr.rsplit (Marc Mueller, PR18673)
Optimizestr.removeprefix andstr.removesuffix (Marc Mueller, PR18672)
Recognize literal types in__match_args__ (Stanislav Terliakov, PR18636)
Fix non extension classes with attribute annotations using forward references (Valentin Stanciu, PR18577)
Use lower-case generic types such aslist[t] in documentation (Jukka Lehtosalo, PR18576)
Improve support forfrozenset (Marc Mueller, PR18571)
Fix wheel build for cp313-win (Marc Mueller, PR18560)
Reduce impact of immortality (introduced in Python 3.12) on reference counting performance (Jukka Lehtosalo, PR18459)
Update math error messages for 3.14 (Marc Mueller, PR18534)
Update math error messages for 3.14 (2) (Marc Mueller, PR18949)
Replace deprecated_PyLong_new withPyLongWriter API (Marc Mueller, PR18532)
Traverse module ancestors when traversing reachable graph nodes during dmypy update (Stanislav Terliakov, PR18906)
Fix crash on multiple unpacks in a bare type application (Stanislav Terliakov, PR18857)
Prevent crash when enum/TypedDict call is stored as a class attribute (Stanislav Terliakov, PR18861)
Fix crash on multiple unpacks in a bare type application (Stanislav Terliakov, PR18857)
Fix crash on type inference against non-normal callables (Ivan Levkivskyi, PR18858)
Fix crash on decorated getter in settable property (Ivan Levkivskyi, PR18787)
Fix crash on callable with*args and suffix against Any (Ivan Levkivskyi, PR18781)
Fix crash on deferred supertype and setter override (Ivan Levkivskyi, PR18649)
Fix crashes on incorrectly detected recursive aliases (Ivan Levkivskyi, PR18625)
Report thatNamedTuple anddataclass are incompatile instead of crashing (Christoph Tyralla, PR18633)
Fix mypy daemon crash (Valentin Stanciu, PR19087)
These are specific to mypy. Mypyc-related performance improvements are discussed elsewhere.
Improve documentation of--strict (lenayoung8, PR18903)
Remove a note aboutfrom__future__importannotations (Ageev Maxim, PR18915)
Improve documentation on type narrowing (Tim Hoffmann, PR18767)
Fix metaclass usage example (Georg, PR18686)
Update documentation onextra_checks flag (Ivan Levkivskyi, PR18537)
FixTypeAlias handling (Alexey Makridenko, PR18960)
Handlearg=None in C extension modules (Anthony Sottile, PR18768)
Fix valid type detection to allow pipe unions (Chad Dombrova, PR18726)
Include simple decorators in stub files (Marc Mueller, PR18489)
Support positional and keyword-only arguments in stubdoc (Paul Ganssle, PR18762)
Fall back toIncomplete if we are unable to determine the module name (Stanislav Terliakov, PR19084)
Make stubtest ignore__slotnames__ (Nick Pope, PR19077)
Fix stubtest tests on 3.14 (Jelle Zijlstra, PR19074)
Support forstrict_bytes in stubtest (Joren Hammudoglu, PR19002)
Understand override (Shantanu, PR18815)
Better checking of runtime arguments with dunder names (Shantanu, PR18756)
Ignore setattr and delattr inherited from object (Stephen Morton, PR18325)
Add--strict-bytes to--strict (wyattscarpenter, PR19049)
Admit that Final variables are never redefined (Stanislav Terliakov, PR19083)
Add special support for@django.cached_property needed indjango-stubs (sobolevn, PR18959)
Do not narrow types toNever with binder (Ivan Levkivskyi, PR18972)
Local forward references should precede global forward references (Ivan Levkivskyi, PR19000)
Do not cache module lookup results in incremental mode that may become invalid (Stanislav Terliakov, PR19044)
Only consider meta variables in ambiguous “any of” constraints (Stanislav Terliakov, PR18986)
Allow accessing__init__ on final classes and when__init__ is final (Stanislav Terliakov, PR19035)
Treat varargs as positional-only (A5rocks, PR19022)
Enable colored output for argparse help in Python 3.14 (Marc Mueller, PR19021)
Fix argparse for Python 3.14 (Marc Mueller, PR19020)
dmypysuggest can now suggest through contextmanager-based decorators (Anthony Sottile, PR18948)
Fix__r<magic_methods>__ being used under the same__<magic_method>__ hook (Arnav Jain, PR18995)
Prioritize.pyi from-stubs packages over bundled.pyi (Joren Hammudoglu, PR19001)
Fix missing subtype check case fortype[T] (Stanislav Terliakov, PR18975)
Fixes to the detection of redundant casts (Anthony Sottile, PR18588)
Make some parse errors non-blocking (Shantanu, PR18941)
Fix PEP 695 type alias with a mix of type arguments (PEP 696) (Marc Mueller, PR18919)
Allow deeper recursion in mypy daemon, better error reporting (Carter Dodd, PR17707)
Fix swapped errors for frozen/non-frozen dataclass inheritance (Nazrawi Demeke, PR18918)
Fix incremental issue with namespace packages (Shantanu, PR18907)
Exclude irrelevant members when narrowing union overlapping with enum (Stanislav Terliakov, PR18897)
Flatten union before contracting literals when checking subtyping (Stanislav Terliakov, PR18898)
Do not addkw_only dataclass fields to__match_args__ (sobolevn, PR18892)
Fix error message when returning long tuple with type mismatch (Thomas Mattone, PR18881)
TreatTypedDict (old-style) aliases as regularTypedDicts (Stanislav Terliakov, PR18852)
Warn about unusedtype:ignore comments when error code is disabled (Brian Schubert, PR18849)
Reject duplicateParamSpec.{args,kwargs} at call site (Stanislav Terliakov, PR18854)
Make detection of enum members more consistent (sobolevn, PR18675)
Admit that**kwargs mapping subtypes may have no direct type parameters (Stanislav Terliakov, PR18850)
Don’t suggesttypes-setuptools forpkg_resources (Shantanu, PR18840)
Suggestscipy-stubs forscipy as non-typeshed stub package (Joren Hammudoglu, PR18832)
Narrow tagged unions in match statements (Gene Parmesan Thomas, PR18791)
Consistently store settable property type (Ivan Levkivskyi, PR18774)
Do not blindly undefer on leaving function (Ivan Levkivskyi, PR18674)
Process superclass methods before subclass methods in semanal (Ivan Levkivskyi, PR18723)
Only defer top-level functions (Ivan Levkivskyi, PR18718)
Add one more type-checking pass (Ivan Levkivskyi, PR18717)
Properly account formember andnonmember in enums (sobolevn, PR18559)
Fix instance vs tuple subtyping edge case (Ivan Levkivskyi, PR18664)
Improve handling of Any/object in variadic generics (Ivan Levkivskyi, PR18643)
Fix handling of named tuples in class match pattern (Ivan Levkivskyi, PR18663)
Fix regression for user config files (Shantanu, PR18656)
Fix dmypy socket issue on GNU/Hurd (Mattias Ellert, PR18630)
Don’t assume that for loop body index variable is always set (Jukka Lehtosalo, PR18631)
Fix overlap check for variadic generics (Ivan Levkivskyi, PR18638)
Improve support forfunctools.partial of overloaded callable protocol (Shantanu, PR18639)
Allow lambdas inexcept* clauses (Stanislav Terliakov, PR18620)
Fix trailing commas in many multiline string options inpyproject.toml (sobolevn, PR18624)
Allow trailing commas forfiles setting inmypy.ini andsetup.ini (sobolevn, PR18621)
Fix “not callable” issue for@dataclass(frozen=True) withFinal attr (sobolevn, PR18572)
Add missing TypedDict special case when checking member access (Stanislav Terliakov, PR18604)
Use lower caselist anddict in invariance notes (Jukka Lehtosalo, PR18594)
Fix inference when class and instance match protocol (Ivan Levkivskyi, PR18587)
Remove support forbuiltins.Any (Marc Mueller, PR18578)
Update the overlapping check for tuples to account for NamedTuples (A5rocks, PR18564)
Fix@deprecated (PEP 702) with normal overloaded methods (Christoph Tyralla, PR18477)
Start propagating end columns/lines fortype-arg errors (A5rocks, PR18533)
Improve handling oftype(x)isFoo checks (Stanislav Terliakov, PR18486)
Suggesttyping.Literal for exit-return error messages (Marc Mueller, PR18541)
Allow redefinitions in except/else/finally (Stanislav Terliakov, PR18515)
Disallow setting Python version using inline config (Shantanu, PR18497)
Improve type inference in tuple multiplication plugin (Shantanu, PR18521)
Add missing line number toyieldfrom with wrong type (Stanislav Terliakov, PR18518)
Hint at argument names when formatting callables with compatible return types in error messages (Stanislav Terliakov, PR18495)
Add better naming and improve compatibility for ad hoc intersections of instances (Christoph Tyralla, PR18506)
Thanks to all mypy contributors who contributed to this release:
A5rocks
Aaron Gokaslan
Advait Dixit
Ageev Maxim
Alexey Makridenko
Ali Hamdan
Anthony Sottile
Arnav Jain
Brian Schubert
bzoracler
Carter Dodd
Chad Dombrova
Christoph Tyralla
Dimitri Papadopoulos Orfanos
Emma Smith
exertustfm
Gene Parmesan Thomas
Georg
Ivan Levkivskyi
Jared Hance
Jelle Zijlstra
Joren Hammudoglu
lenayoung8
Marc Mueller
Mattias Ellert
Michael J. Sullivan
Michael R. Crusoe
Nazrawi Demeke
Nick Pope
Paul Ganssle
Shantanu
sobolevn
Stanislav Terliakov
Stephen Morton
Thomas Mattone
Tim Hoffmann
Tim Ruffing
Valentin Stanciu
Wesley Collin Wright
wyattscarpenter
I’d also like to thank my employer, Dropbox, for supporting mypy development.
We’ve just uploaded mypy 1.15 to the Python Package Index (PyPI).Mypy is a static type checker for Python. This release includes new features, performanceimprovements and bug fixes. You can install it as follows:
python3 -m pip install -U mypy
You can read the full documentation for this release onRead the Docs.
Mypy is up to 40% faster in some use cases. This improvement comes largely from tuning the performanceof the garbage collector. Additionally, the release includes several micro-optimizations that maybe impactful for large projects.
Contributed by Jukka Lehtosalo
For best performance, mypy can be compiled to C extension modules using mypyc. This makesmypy 3-5x faster than when interpreted with pure Python. We now build and upload mypycaccelerated mypy wheels formanylinux_aarch64 to PyPI, making it easy for Linux users onARM platforms to realise this speedup – justpipinstall the latest mypy.
Contributed by Christian Bundy and Marc Mueller(PRmypy_mypyc-wheels#76,PRmypy_mypyc-wheels#89).
--strict-bytes¶By default, mypy treatsbytearray andmemoryview values as assignable to thebytestype, for historical reasons. Use the--strict-bytes flag to disable thisbehavior.PEP 688 specified the removal of thisspecial case. The flag will be enabled by default inmypy 2.0.
Contributed by Ali Hamdan (PR18263) andShantanu Jain (PR13952).
This change results in mypy better modelling control flow within loops and hence detectingseveral previously ignored issues. In some cases, this change may require additionalexplicit variable annotations.
Contributed by Christoph Tyralla (PR18180,PR18433).
(Speaking of partial types, remember that we plan to enable--local-partial-typesby default inmypy 2.0.)
Mypy will now walk up the filesystem (up until a repository or file system root) to discoverconfiguration files. See themypy configuration file documentationfor more details.
Contributed by Mikhail Shiryaev and Shantanu Jain(PR16965, PR18482)
Mypy now uses more correct line numbers for decorators and slice expressions. In some cases,you may have to change the location of a#type:ignore comment.
Mypy no longer supports running with Python 3.8, which has reached end-of-life.When running mypy with Python 3.9+, it is still possible to type check codethat needs to support Python 3.8 with the--python-version3.8 argument.Support for this will be dropped in the first half of 2025!
Contributed by Marc Mueller (PR17492).
Fix__init__ for classes with@attr.s(slots=True) (Advait Dixit, PR18447)
Report error for nested class instead of crashing (Valentin Stanciu, PR18460)
FixInitVar for dataclasses (Advait Dixit, PR18319)
Remove unnecessary mypyc files from wheels (Marc Mueller, PR18416)
Fix issues with relative imports (Advait Dixit, PR18286)
Add faster primitive for some list get item operations (Jukka Lehtosalo, PR18136)
Fix iteration overNamedTuple objects (Advait Dixit, PR18254)
Mark mypyc package withpy.typed (bzoracler, PR18253)
Fix list index while checking forEnum class (Advait Dixit, PR18426)
Improve dataclass init signatures (Marc Mueller, PR18430)
Preservedataclass_transform decorator (Marc Mueller, PR18418)
FixUnpackType for 3.11+ (Marc Mueller, PR18421)
Improveself annotations (Marc Mueller, PR18420)
PrintInspectError traceback in stubgenwalk_packages when verbose is specified (Gareth, PR18224)
Prevent crash withUnpack of a fixed tuple in PEP695 type alias (Stanislav Terliakov, PR18451)
Fix crash with--cache-fine-grained--cache-dir=/dev/null (Shantanu, PR18457)
Prevent crashing whenmatch arms use name of existing callable (Stanislav Terliakov, PR18449)
Gracefully handle encoding errors when writing to stdout (Brian Schubert, PR18292)
Prevent crash on generic NamedTuple with unresolved typevar bound (Stanislav Terliakov, PR18585)
Add inline tabs to documentation (Marc Mueller, PR18262)
Document anyTYPE_CHECKING name works (Shantanu, PR18443)
Update documentation to not mention 3.8 where possible (sobolevn, PR18455)
Mentionignore_errors in exclude documentation (Shantanu, PR18412)
AddSelf misuse to common issues (Shantanu, PR18261)
Fix literal context for ternary expressions (Ivan Levkivskyi, PR18545)
Ignoredataclass.__replace__ LSP violations (Marc Mueller, PR18464)
Bindself to the class being defined when checking multiple inheritance (Stanislav Terliakov, PR18465)
Fix attribute type resolution with multiple inheritance (Stanislav Terliakov, PR18415)
Improve security of our GitHub Actions (sobolevn, PR18413)
Unwraptype[Union[...]] when solving type variable constraints (Stanislav Terliakov, PR18266)
AllowAny to match sequence patterns in match/case (Stanislav Terliakov, PR18448)
Fix parent generics mapping when overriding generic attribute with property (Stanislav Terliakov, PR18441)
Add dedicated error code for explicitAny (Shantanu, PR18398)
Reject invalidParamSpec locations (Stanislav Terliakov, PR18278)
Stop suggesting stubs that have been removed from typeshed (Shantanu, PR18373)
Allow inverting--local-partial-types (Shantanu, PR18377)
Allow to useFinal andClassVar after Python 3.13 (정승원, PR18358)
Update suggestions to include latest stubs in typeshed (Shantanu, PR18366)
Fix--install-types masking failure details (wyattscarpenter, PR17485)
Reject promotions when checking against protocols (Christoph Tyralla, PR18360)
Don’t erase type object arguments in diagnostics (Shantanu, PR18352)
Clarify status indmypystatus output (Kcornw, PR18331)
Disallow no-argument generic aliases when using PEP 613 explicit aliases (Brian Schubert, PR18173)
Suppress errors for unreachable branches in conditional expressions (Brian Schubert, PR18295)
Do not allowClassVar andFinal inTypedDict andNamedTuple (sobolevn, PR18281)
Report error if not enough or too many types provided toTypeAliasType (bzoracler, PR18308)
Use more precise context forTypedDict plugin errors (Brian Schubert, PR18293)
Use more precise context for invalid type argument errors (Brian Schubert, PR18290)
Do not allowtype[] to containLiteral types (sobolevn, PR18276)
Allow bytearray/bytes comparisons with--strict-bytes (Jukka Lehtosalo, PR18255)
Thanks to all mypy contributors who contributed to this release:
Advait Dixit
Ali Hamdan
Brian Schubert
bzoracler
Cameron Matsui
Christoph Tyralla
Gareth
Ivan Levkivskyi
Jukka Lehtosalo
Kcornw
Marc Mueller
Mikhail f. Shiryaev
Shantanu
sobolevn
Stanislav Terliakov
Stephen Morton
Valentin Stanciu
Viktor Szépe
wyattscarpenter
정승원
I’d also like to thank my employer, Dropbox, for supporting mypy development.
We’ve just uploaded mypy 1.14 to the Python Package Index (PyPI).Mypy is a static type checker for Python. This release includes new features and bug fixes.You can install it as follows:
python3 -m pip install -U mypy
You can read the full documentation for this release onRead the Docs.
As per the updatedtyping specification for enums,enum members must be left unannotated.
classPet(Enum):CAT=1# Member attributeDOG=2# Member attribute# New error: Enum members must be left unannotatedWOLF:int=3species:str# Considered a non-member attribute
In particular, the specification change can result in issues in type stubs (.pyi files), sincehistorically it was common to leave the value absent:
# In a type stub (.pyi file)classPet(Enum):# Change in semantics: previously considered members,# now non-member attributesCAT:intDOG:int# Mypy will now issue a warning if it detects this# situation in type stubs:# > Detected enum "Pet" in a type stub with zero# > members. There is a chance this is due to a recent# > change in the semantics of enum membership. If so,# > use `member = value` to mark an enum member,# > instead of `member: type`classPet(Enum):# As per the specification, you should now do one of# the following:DOG=1# Member attribute with value 1 and known typeWOLF=cast(int,...)# Member attribute with unknown# value but known typeLION=...# Member attribute with unknown value and# # unknown type
Contributed by Terence Honles (PR17207) andShantanu Jain (PR18068).
Mypy can now issue errors or notes when code imports a deprecated featureexplicitly with afrommodimportdepr statement, or uses a deprecated featureimported otherwise or defined locally. Features are considered deprecated whendecorated withwarnings.deprecated, as specified inPEP 702.
You can enable the error code via--enable-error-code=deprecated on the mypycommand line orenable_error_code=deprecated in the mypy config file.Use the command line flag--report-deprecated-as-note or config file optionreport_deprecated_as_note=True to turn all such errors into notes.
Deprecation errors will be enabled by default in a future mypy version.
This feature was contributed by Christoph Tyralla.
List of changes:
Add basic support for PEP 702 (@deprecated) (Christoph Tyralla, PR17476)
Support descriptors with@deprecated (Christoph Tyralla, PR18090)
Make “deprecated” note an error, disabled by default (Valentin Stanciu, PR18192)
Consider all possible type positions with@deprecated (Christoph Tyralla, PR17926)
Improve the handling of explicit type annotations in assignment statements with@deprecated (Christoph Tyralla, PR17899)
Mypy normally doesn’t analyze imports from third-party modules (installed using pip, for example)if there are no stubs or a py.typed marker file. To force mypy to analyze these imports, youcan now use the--follow-untyped-imports flag or set thefollow_untyped_importsconfig file option to True. This can be set either in the global section of your mypy configfile, or individually on a per-module basis.
This feature was contributed by Jannick Kremer.
List of changes:
Mypy now supports type variable defaults using the new syntax described in PEP 696, whichwas introduced in Python 3.13. Example:
@dataclassclassBox[T=int]:# Set default for "T"value:T|None=Nonereveal_type(Box())# type is Box[int], since it's the defaultreveal_type(Box(value="Hello World!"))# type is Box[str]
This feature was contributed by Marc Mueller (PR17985).
Mypy now preserves the literal type of for loop index variables, to supportTypedDictlookups. Example:
fromtypingimportTypedDictclassX(TypedDict):hourly:intdaily:intdeffunc(x:X)->int:s=0forvarin("hourly","daily"):# "Union[Literal['hourly']?, Literal['daily']?]"reveal_type(var)# x[var] no longer triggers a literal-required errors+=x[var]returns
This was contributed by Marc Mueller (PR18014).
Document optimized bytes operations and additional str operations (Jukka Lehtosalo, PR18242)
Add primitives and specialization forord() (Jukka Lehtosalo, PR18240)
Optimizestr.encode with specializations for common used encodings (Valentin Stanciu, PR18232)
Fix fall back to generic operation for staticmethod and classmethod (Advait Dixit, PR18228)
Support unicode surrogates in string literals (Jukka Lehtosalo, PR18209)
Fix index variable in for loop withbuiltins.enumerate (Advait Dixit, PR18202)
Fix check for enum classes (Advait Dixit, PR18178)
Fix loading type from imported modules (Advait Dixit, PR18158)
Fix initializers of final attributes in class body (Jared Hance, PR18031)
Fix name generation for modules with similar full names (aatle, PR18001)
Fix relative imports in__init__.py (Shantanu, PR17979)
Optimize dunder methods (jairov4, PR17934)
Replace deprecated_PyDict_GetItemStringWithError (Marc Mueller, PR17930)
Fix wheel build for cp313-win (Marc Mueller, PR17941)
Use public PyGen_GetCode instead of vendored implementation (Marc Mueller, PR17931)
Optimize calls to final classes (jairov4, PR17886)
Support ellipsis (...) expressions in class bodies (Newbyte, PR17923)
Syncpythoncapi_compat.h (Marc Mueller, PR17929)
Addruntests.pymypyc-fast for running fast mypyc tests (Jukka Lehtosalo, PR17906)
Update config file documentation (sobolevn, PR18103)
Improve contributor documentation for Windows (ag-tafe, PR18097)
Correct note about--disallow-any-generics flag in documentation (Abel Sen, PR18055)
Further caution against--follow-imports=skip (Shantanu, PR18048)
Fix the edit page button link in documentation (Kanishk Pachauri, PR17933)
Allow enum members to have type objects as values (Jukka Lehtosalo, PR19160)
ShowProtocol__call__ for arguments with incompatible types (MechanicalConstruct, PR18214)
Make join and meet symmetric withstrict_optional (MechanicalConstruct, PR18227)
Preserve block unreachablility when checking function definitions with constrained TypeVars (Brian Schubert, PR18217)
Do not include non-init fields in the synthesized__replace__ method for dataclasses (Victorien, PR18221)
DisallowTypeVar constraints parameterized by type variables (Brian Schubert, PR18186)
Always complain about invalid varargs and varkwargs (Shantanu, PR18207)
Set default strict_optional state to True (Shantanu, PR18198)
Preserve type variable default None in type alias (Sukhorosov Aleksey, PR18197)
Add checks for invalid usage of continue/break/return inexcept* block (coldwolverine, PR18132)
Do not consider bare TypeVar not overlapping with None for reachability analysis (Stanislav Terliakov, PR18138)
Special casetypes.DynamicClassAttribute as property-like (Stephen Morton, PR18150)
Disallow bareParamSpec in type aliases (Brian Schubert, PR18174)
Move long_description metadata to pyproject.toml (Marc Mueller, PR18172)
Support==-based narrowing of Optional (Christoph Tyralla, PR18163)
Allow TypedDict assignment of Required item to NotRequired ReadOnly item (Brian Schubert, PR18164)
Allow nesting of Annotated with TypedDict special forms inside TypedDicts (Brian Schubert, PR18165)
Infer generic type arguments for slice expressions (Brian Schubert, PR18160)
Fix checking of match sequence pattern against bounded type variables (Brian Schubert, PR18091)
Fix incorrect truthyness for Enum types and literals (David Salvisberg, PR17337)
Move static project metadata to pyproject.toml (Marc Mueller, PR18146)
Fallback to stdlib json if integer exceeds 64-bit range (q0w, PR18148)
Fix ‘or’ pattern structural matching exhaustiveness (yihong, PR18119)
Fix type inference of positional parameter in class pattern involving builtin subtype (Brian Schubert, PR18141)
Fix[override] error with no line number when argument node has no line number (Brian Schubert, PR18122)
Fix some dmypy crashes (Ivan Levkivskyi, PR18098)
Fix subtyping between instance type and overloaded (Shantanu, PR18102)
Clean up new_semantic_analyzer config (Shantanu, PR18071)
Issue warning for enum with no members in stub (Shantanu, PR18068)
Fix enum attributes are not members (Terence Honles, PR17207)
Fix crash when checking slice expression with step 0 in tuple index (Brian Schubert, PR18063)
Allow union-with-callable attributes to be overridden by methods (Brian Schubert, PR18018)
Emit[mutable-override] for covariant override of attribute with method (Brian Schubert, PR18058)
Support ParamSpec mapping withfunctools.partial (Stanislav Terliakov, PR17355)
Fix approved stub ignore, remove normpath (Shantanu, PR18045)
Makedisallow-any-unimported flag invertible (Séamus Ó Ceanainn, PR18030)
Filter to possible package paths before trying to resolve a module (falsedrow, PR18038)
Fix overlap check for ParamSpec types (Jukka Lehtosalo, PR18040)
Do not prioritize ParamSpec signatures during overload resolution (Stanislav Terliakov, PR18033)
Fix ternary union for literals (Ivan Levkivskyi, PR18023)
Fix compatibility checks for conditional function definitions using decorators (Brian Schubert, PR18020)
TypeGuard should be bool not Any when matching TypeVar (Evgeniy Slobodkin, PR17145)
Fix convert-cache tool (Shantanu, PR17974)
Fix generator comprehension with mypyc (Shantanu, PR17969)
Fix crash issue when using shadowfile with pretty (Max Chang, PR17894)
Fix multiple nested classes with new generics syntax (Max Chang, PR17820)
Better error formypy-ppackage without py.typed (Joe Gordon, PR17908)
Emit error forraiseNotImplemented (Brian Schubert, PR17890)
Addis_lvalue attribute to AttributeContext (Brian Schubert, PR17881)
Thanks to all mypy contributors who contributed to this release:
aatle
Abel Sen
Advait Dixit
ag-tafe
Alex Waygood
Ali Hamdan
Brian Schubert
Carlton Gibson
Chad Dombrova
Chelsea Durazo
chiri
Christoph Tyralla
coldwolverine
David Salvisberg
Ekin Dursun
Evgeniy Slobodkin
falsedrow
Gaurav Giri
Ihor
Ivan Levkivskyi
jairov4
Jannick Kremer
Jared Hance
Jelle Zijlstra
jianghuyiyuan
Joe Gordon
John Doknjas
Jukka Lehtosalo
Kanishk Pachauri
Marc Mueller
Max Chang
MechanicalConstruct
Newbyte
q0w
Ruslan Sayfutdinov
Sebastian Rittau
Shantanu
sobolevn
Stanislav Terliakov
Stephen Morton
Sukhorosov Aleksey
Séamus Ó Ceanainn
Terence Honles
Valentin Stanciu
vasiliy
Victorien
yihong
I’d also like to thank my employer, Dropbox, for supporting mypy development.
We’ve just uploaded mypy 1.13 to the Python Package Index (PyPI).Mypy is a static type checker for Python. You can install it as follows:
python3 -m pip install -U mypy
You can read the full documentation for this release onRead the Docs.
Note that unlike typical releases, Mypy 1.13 does not have any changes to type checking semanticsfrom 1.12.1.
Mypy 1.13 contains several performance improvements. Users can expect mypy to be 5-20% faster.In environments with long search paths (such as environments using many editable installs), mypycan be significantly faster, e.g. 2.2x faster in the use case targeted by these improvements.
Mypy 1.13 allows use of theorjson library for handling the cache instead of the stdlibjson,for improved performance. You can ensure the presence oforjson using thefaster-cache extra:
python3 -m pip install -U mypy[faster-cache]
Mypy may depend onorjson by default in the future.
These improvements were contributed by Shantanu.
List of changes:
Significantly speed up file handling error paths (Shantanu, PR17920)
Use fast path in modulefinder more often (Shantanu, PR17950)
Let mypyc optimise os.path.join (Shantanu, PR17949)
Make is_sub_path faster (Shantanu, PR17962)
Speed up stubs suggestions (Shantanu, PR17965)
Use sha1 for hashing (Shantanu, PR17953)
Use orjson instead of json, when available (Shantanu, PR17955)
Add faster-cache extra, test in CI (Shantanu, PR17978)
Thanks to all mypy contributors who contributed to this release:
Shantanu Jain
Jukka Lehtosalo
We’ve just uploaded mypy 1.12 to the Python Package Index (PyPI). Mypy is a static typechecker 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 onRead the Docs.
Support for the new type parameter syntax introduced in Python 3.12 is now enabled by default,documented, and no longer experimental. It was available through a feature flag inmypy 1.11 as an experimental feature.
This example demonstrates the new syntax:
# Generic functiondeff[T](x:T)->T:...reveal_type(f(1))# Revealed type is 'int'# Generic classclassC[T]:def__init__(self,x:T)->None:self.x=xc=C('a')reveal_type(c.x)# Revealed type is 'str'# Type aliastypeA[T]=C[list[T]]
For more information, refer to thedocumentation.
These improvements are included:
Document Python 3.12 type parameter syntax (Jukka Lehtosalo, PR17816)
Further documentation updates (Jukka Lehtosalo, PR17826)
Allow Self return types with contravariance (Jukka Lehtosalo, PR17786)
Enable new type parameter syntax by default (Jukka Lehtosalo, PR17798)
Generate error if new-style type alias used as base class (Jukka Lehtosalo, PR17789)
Inherit variance if base class has explicit variance (Jukka Lehtosalo, PR17787)
Fix crash on invalid type var reference (Jukka Lehtosalo, PR17788)
Fix covariance of frozen dataclasses (Jukka Lehtosalo, PR17783)
Allow covariance with attribute that has “_” name prefix (Jukka Lehtosalo, PR17782)
SupportAnnotated[...] in new-style type aliases (Jukka Lehtosalo, PR17777)
Fix nested generic classes (Jukka Lehtosalo, PR17776)
Add detection and error reporting for the use of incorrect expressions within the scope of a type parameter and a type alias (Kirill Podoprigora, PR17560)
This release adds partial support for Python 3.13 features and compiled binaries forPython 3.13. Mypyc now also supports Python 3.13.
In particular, these features are supported:
Various new stdlib features and changes (through typeshed stub improvements)
typing.ReadOnly (see below for more)
typing.TypeIs (added in mypy 1.10,PEP 742)
Type parameter defaults when using the legacy syntax (PEP 696)
These features are not supported yet:
warnings.deprecated (PEP 702)
Type parameter defaults when using Python 3.12 type parameter syntax
Mypyc now supports Python 3.13. This was contributed by Marc Mueller, with additionalfixes by Jukka Lehtosalo. Free threaded Python 3.13 builds are not supported yet.
List of changes:
Add additional includes for Python 3.13 (Marc Mueller, PR17506)
Add another include for Python 3.13 (Marc Mueller, PR17509)
Fix ManagedDict functions for Python 3.13 (Marc Mueller, PR17507)
Update mypyc test output for Python 3.13 (Marc Mueller, PR17508)
FixPyUnicode functions for Python 3.13 (Marc Mueller, PR17504)
Fix_PyObject_LookupAttrId for Python 3.13 (Marc Mueller, PR17505)
Fix_PyList_Extend for Python 3.13 (Marc Mueller, PR17503)
Fixgen_is_coroutine for Python 3.13 (Marc Mueller, PR17501)
Fix_PyObject_FastCall for Python 3.13 (Marc Mueller, PR17502)
Avoid uses of_PyObject_CallMethodOneArg on 3.13 (Jukka Lehtosalo, PR17526)
Don’t rely on_PyType_CalculateMetaclass on 3.13 (Jukka Lehtosalo, PR17525)
Don’t use_PyUnicode_FastCopyCharacters on 3.13 (Jukka Lehtosalo, PR17524)
Don’t use_PyUnicode_EQ on 3.13, as it’s no longer exported (Jukka Lehtosalo, PR17523)
Mypy now always tries to infer a union type for a conditional expression if left and rightoperand types are different. This results in more precise inferred types and lets mypy detectmore issues. Example:
s="foo"ifcond()else1# Type of "s" is now "str | int" (it used to be "object")
Notably, if one of the operands has typeAny, the type of a conditional expression isnow<type>|Any. Previously the inferred type was justAny. The new type essentiallyindicates that the value can be of type<type>, and potentially of some (unknown) type.Most operations performed on the result must also be valid for<type>.Example where this is relevant:
fromtypingimportAnydeffunc(a:Any,b:bool)->None:x=aifbelseNone# Type of x is "Any | None"print(x.y)# Error: None has no attribute "y"
This feature was contributed by Ivan Levkivskyi (PR17427).
You can now usetyping.ReadOnly to specity TypedDict items asread-only (PEP 705):
fromtypingimportTypedDict# Or "from typing ..." on Python 3.13fromtyping_extensionsimportReadOnlyclassTD(TypedDict):a:intb:ReadOnly[int]d:TD={"a":1,"b":2}d["a"]=3# OKd["b"]=5# Error: "b" is ReadOnly
This feature was contributed by Nikita Sobolev (PR17644).
We are planning to drop support for Python 3.8 in the next mypy feature release or theone after that. Python 3.8 reaches end of life in October 2024.
We are planning to enable--local-partial-types by default in mypy 2.0. This willoften require at least minor code changes. This option is implicitly enabled by mypydaemon, so this makes the behavior of daemon and non-daemon modes consistent.
We recommend that mypy users start using local partial types soon (or to explicitly disablethem) to prepare for the change.
This can also be configured in a mypy configuration file:
local_partial_types=True
For more information, refer to thedocumentation.
Mypy documentation now uses modern syntax variants and imports in many examples. Someexamples no longer work on Python 3.8, which is the earliest Python version that mypy supports.
Notably,Iterable and other protocols/ABCs are imported fromcollections.abc instead oftyping:
fromcollections.abcimportIterable,Callable
Examples also avoid the upper-case aliases to built-in types:list[str] is used insteadofList[str]. TheX|Y union type syntax introduced in Python 3.10 is also now prevalent.
List of documentation updates:
Document--output=json CLI option (Edgar Ramírez Mondragón, PR17611)
Update various references to deprecated type aliases in docs (Jukka Lehtosalo, PR17829)
Make “X | Y” union syntax more prominent in documentation (Jukka Lehtosalo, PR17835)
Discuss upper bounds before self types in documentation (Jukka Lehtosalo, PR17827)
Make changelog visible in mypy documentation (quinn-sasha, PR17742)
List all incomplete features in--enable-incomplete-feature docs (sobolevn, PR17633)
Remove the explicit setting of a pygments theme (Pradyun Gedam, PR17571)
Document ReadOnly with TypedDict (Jukka Lehtosalo, PR17905)
Document TypeIs (Chelsea Durazo, PR17821)
Mypy now supports a non-standard, experimental syntax for defining anonymous TypedDicts.Example:
deffunc(n:str,y:int)->{"name":str,"year":int}:return{"name":n,"year":y}
The feature is disabled by default. Use--enable-incomplete-feature=InlineTypedDict toenable it.We might remove this feature in a future release.
This feature was contributed by Ivan Levkivskyi (PR17457).
Fix crash on literal class-level keywords (sobolevn, PR17663)
Stubgen add--version (sobolevn, PR17662)
Fixstubgen--no-analysis/--parse-only docs (sobolevn, PR17632)
Include keyword only args when generating signatures in stubgenc (Eric Mark Martin, PR17448)
Add support for detectingLiteral types when extracting types from docstrings (Michael Carlstrom, PR17441)
UseGenerator type var defaults (Sebastian Rittau, PR17670)
Report error if using unsupported type parameter defaults (Jukka Lehtosalo, PR17876)
Fix re-processing cross-reference in mypy daemon when node kind changes (Ivan Levkivskyi, PR17883)
Don’t use equality to narrow when value is IntEnum/StrEnum (Jukka Lehtosalo, PR17866)
Don’t consider None vs IntEnum comparison ambiguous (Jukka Lehtosalo, PR17877)
Fix narrowing of IntEnum and StrEnum types (Jukka Lehtosalo, PR17874)
Filter overload items based on self type during type inference (Jukka Lehtosalo, PR17873)
Enable negative narrowing of union TypeVar upper bounds (Brian Schubert, PR17850)
Fix issue with member expression formatting (Brian Schubert, PR17848)
Avoid type size explosion when expanding types (Jukka Lehtosalo, PR17842)
Fix negative narrowing of tuples in match statement (Brian Schubert, PR17817)
Narrow falsey str/bytes/int to literal type (Brian Schubert, PR17818)
Test against latest Python 3.13, make testing 3.14 easy (Shantanu, PR17812)
Reject ParamSpec-typed callables calls with insufficient arguments (Stanislav Terliakov, PR17323)
Fix crash when passing too many type arguments to generic base class accepting single ParamSpec (Brian Schubert, PR17770)
Fix TypeVar upper bounds sometimes not being displayed in pretty callables (Brian Schubert, PR17802)
Added error code for overlapping function signatures (Katrina Connors, PR17597)
Check fortruthy-bool innot... unary expressions (sobolevn, PR17773)
Add missing lines-covered and lines-valid attributes (Soubhik Kumar Mitra, PR17738)
Fix another crash scenario with recursive tuple types (Ivan Levkivskyi, PR17708)
Resolve TypeVar upper bounds infunctools.partial (Shantanu, PR17660)
Always reset binder when checking deferred nodes (Ivan Levkivskyi, PR17643)
Fix crash on a callable attribute with single unpack (Ivan Levkivskyi, PR17641)
Fix mismatched signature between checker plugin API and implementation (bzoracler, PR17343)
Indexing a type also produces a GenericAlias (Shantanu, PR17546)
Fix crash on self-type in callable protocol (Ivan Levkivskyi, PR17499)
Fix crash on NamedTuple with method and error in function (Ivan Levkivskyi, PR17498)
Add__replace__ for dataclasses in 3.13 (Max Muoto, PR17469)
Fix help message for--no-namespace-packages (Raphael Krupinski, PR17472)
Fix typechecking for async generators (Danny Yang, PR17452)
Fix strict optional handling in attrs plugin (Ivan Levkivskyi, PR17451)
Allow mixing ParamSpec and TypeVarTuple in Generic (Ivan Levkivskyi, PR17450)
Improvements tofunctools.partial of types (Shantanu, PR17898)
Make ReadOnly TypedDict items covariant (Jukka Lehtosalo, PR17904)
Fix union callees withfunctools.partial (Jukka Lehtosalo, PR17903)
Improve handling of generic functions withfunctools.partial (Ivan Levkivskyi, PR17925)
Please seegit log for full list of standard library typeshed stub changes.
Fix crash when showing partially analyzed type in error message (Ivan Levkivskyi, PR17961)
Fix iteration over union (when self type is involved) (Shantanu, PR17976)
Fix type object with type var default in union context (Jukka Lehtosalo, PR17991)
Revert change toos.path stubs affecting use ofos.PathLike[Any] (Shantanu, PR17995)
Thanks to all mypy contributors who contributed to this release:
Ali Hamdan
Anders Kaseorg
Bénédikt Tran
Brian Schubert
bzoracler
Chelsea Durazo
Danny Yang
Edgar Ramírez Mondragón
Eric Mark Martin
InSync
Ivan Levkivskyi
Jordandev678
Katrina Connors
Kirill Podoprigora
Marc Mueller
Max Muoto
Max Murin
Michael Carlstrom
Michael I Chen
Pradyun Gedam
quinn-sasha
Raphael Krupinski
Sebastian Rittau
Shantanu
sobolevn
Soubhik Kumar Mitra
Stanislav Terliakov
wyattscarpenter
I’d also like to thank my employer, Dropbox, for supporting mypy development.
We’ve just uploaded mypy 1.11 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 onRead the Docs.
Mypy now supports the new type parameter syntax introduced in Python 3.12 (PEP 695).This feature is still experimental and must be enabled with the--enable-incomplete-feature=NewGenericSyntax flag, or withenable_incomplete_feature=NewGenericSyntax in the mypy configuration file.We plan to enable this by default in the next mypy feature release.
This example demonstrates the new syntax:
# Generic functiondeff[T](x:T)->T:...reveal_type(f(1))# Revealed type is 'int'# Generic classclassC[T]:def__init__(self,x:T)->None:self.x=xc=C('a')reveal_type(c.x)# Revealed type is 'str'# Type aliastypeA[T]=C[list[T]]
This feature was contributed by Jukka Lehtosalo.
functools.partial¶Mypy now type checks uses offunctools.partial. Previously mypy would accept arbitrary arguments.
This example will now produce an error:
fromfunctoolsimportpartialdeff(a:int,b:str)->None:...g=partial(f,1)# Argument has incompatible type "int"; expected "str"g(11)
This feature was contributed by Shantanu (PR16939).
Past mypy versions didn’t check if untyped methods were compatible with overridden methods. This would result in false negatives. Now mypy performs these checks when using--check-untyped-defs.
For example, this now generates an error if using--check-untyped-defs:
classBase:deff(self,x:int=0)->None:...classDerived(Base):# Signature incompatible with "Base"deff(self):...
This feature was contributed by Steven Troxler (PR17276).
The new polymorphic inference algorithm introduced in mypy 1.5 is now used in more situations. This improves type inference involving generic higher-order functions, in particular.
This feature was contributed by Ivan Levkivskyi (PR17348).
Mypy now uses unions of tuple item types in certain contexts to enable more precise inferred types. Example:
forxin(1,'x'):# Previously inferred as 'object'reveal_type(x)# Revealed type is 'int | str'
This was also contributed by Ivan Levkivskyi (PR17408).
The details of how mypy checks if two@overload signatures are unsafely overlapping were overhauled. This both fixes some false positives, and allows mypy to detect additional unsafe signatures.
This feature was contributed by Ivan Levkivskyi (PR17392).
Mypy now allows more expressions that evaluate to valid type annotations in all expression contexts. The inferred types of these expressions are also sometimes more precise. Previously they were oftenobject.
This example uses a union type that includes a callable type as an expression, and it no longer generates an error:
fromtypingimportCallableprint(Callable[[],int]|None)# No error
This feature was contributed by Jukka Lehtosalo (PR17404).
Mypyc now supports the new syntax for generics introduced in Python 3.12 (see above). Another notable improvement is significantly faster basic operations onint values.
Support Python 3.12 syntax for generic functions and classes (Jukka Lehtosalo, PR17357)
Support Python 3.12 type alias syntax (Jukka Lehtosalo, PR17384)
Fix ParamSpec (Shantanu, PR17309)
Inline fast paths of integer unboxing operations (Jukka Lehtosalo, PR17266)
Inline tagged integer arithmetic and bitwise operations (Jukka Lehtosalo, PR17265)
Allow specifying primitives as pure (Jukka Lehtosalo, PR17263)
Add error format support and JSON output option via--outputjson (Tushar Sadhwani, PR11396)
Supportenum.member in Python 3.11+ (Nikita Sobolev, PR17382)
Supportenum.nonmember in Python 3.11+ (Nikita Sobolev, PR17376)
Supportnamedtuple.__replace__ in Python 3.13 (Shantanu, PR17259)
Supportrename=True in collections.namedtuple (Jelle Zijlstra, PR17247)
Add support for__spec__ (Shantanu, PR14739)
Mention--enable-incomplete-feature=NewGenericSyntax in messages (Shantanu, PR17462)
Do not report plugin-generated methods withexplicit-override (sobolevn, PR17433)
Use and display namespaces for function type variables (Ivan Levkivskyi, PR17311)
Fix false positive for Final local scope variable in Protocol (GiorgosPapoutsakis, PR17308)
Use Never in more messages, use ambiguous in join (Shantanu, PR17304)
Log full path to config file in verbose output (dexterkennedy, PR17180)
Added[prop-decorator] code for unsupported property decorators (#14461) (Christopher Barber, PR16571)
Suppress second error message with:= and[truthy-bool] (Nikita Sobolev, PR15941)
Generate error for assignment of functional Enum to variable of different name (Shantanu, PR16805)
Fix error reporting on cached run after uninstallation of third party library (Shantanu, PR17420)
Fix daemon crash on invalid type in TypedDict (Ivan Levkivskyi, PR17495)
Fix crash and bugs related topartial() (Ivan Levkivskyi, PR17423)
Fix crash when overriding with unpacked TypedDict (Ivan Levkivskyi, PR17359)
Fix crash on TypedDict unpacking for ParamSpec (Ivan Levkivskyi, PR17358)
Fix crash involving recursive union of tuples (Ivan Levkivskyi, PR17353)
Fix crash on invalid callable property override (Ivan Levkivskyi, PR17352)
Fix crash on unpacking self in NamedTuple (Ivan Levkivskyi, PR17351)
Fix crash on recursive alias with an optional type (Ivan Levkivskyi, PR17350)
Fix crash on type comment inside generic definitions (Bénédikt Tran, PR16849)
Use inline config in documentation for optional error codes (Shantanu, PR17374)
Use lower-case generics in documentation (Seo Sanghyeon, PR17176)
Add documentation for show-error-code-links (GiorgosPapoutsakis, PR17144)
Update CONTRIBUTING.md to include commands for Windows (GiorgosPapoutsakis, PR17142)
Fix ParamSpec inference against TypeVarTuple (Ivan Levkivskyi, PR17431)
Fix explicit type forpartial (Ivan Levkivskyi, PR17424)
Always allow lambda calls (Ivan Levkivskyi, PR17430)
Fix isinstance checks with PEP 604 unions containing None (Shantanu, PR17415)
Fix self-referential upper bound in new-style type variables (Ivan Levkivskyi, PR17407)
Consider overlap between instances and callables (Ivan Levkivskyi, PR17389)
Allow new-style self-types in classmethods (Ivan Levkivskyi, PR17381)
Fix isinstance with type aliases to PEP 604 unions (Shantanu, PR17371)
Properly handle unpacks in overlap checks (Ivan Levkivskyi, PR17356)
Fix type application for classes with generic constructors (Ivan Levkivskyi, PR17354)
Updatetyping_extensions to >=4.6.0 to fix Python 3.12 error (Ben Brown, PR17312)
Avoid “does not return” error in lambda (Shantanu, PR17294)
Fix bug with descriptors in non-strict-optional mode (Max Murin, PR17293)
Don’t leak unreachability from lambda body to surrounding scope (Anders Kaseorg, PR17287)
Fix issues with non-ASCII characters on Windows (Alexander Leopold Shon, PR17275)
Fix for type narrowing of negative integer literals (gilesgc, PR17256)
Fix confusion between .py and .pyi files in mypy daemon (Valentin Stanciu, PR17245)
Fix type oftuple[X,Y] expression (urnest, PR17235)
Don’t forget that aTypedDict was wrapped inUnpack after aname-defined error occurred (Christoph Tyralla, PR17226)
Mark annotated argument as having an explicit, not inferred type (bzoracler, PR17217)
Don’t consider Enum private attributes as enum members (Ali Hamdan, PR17182)
Fix Literal strings containing pipe characters (Jelle Zijlstra, PR17148)
Please seegit log for full list of standard library typeshed stub changes.
Thanks to all mypy contributors who contributed to this release:
Alex Waygood
Alexander Leopold Shon
Ali Hamdan
Anders Kaseorg
Ben Brown
Bénédikt Tran
bzoracler
Christoph Tyralla
Christopher Barber
dexterkennedy
gilesgc
GiorgosPapoutsakis
Ivan Levkivskyi
Jelle Zijlstra
Jukka Lehtosalo
Marc Mueller
Matthieu Devlin
Michael R. Crusoe
Nikita Sobolev
Seo Sanghyeon
Shantanu
sobolevn
Steven Troxler
Tadeu Manoel
Tamir Duberstein
Tushar Sadhwani
urnest
Valentin Stanciu
I’d also like to thank my employer, Dropbox, for supporting mypy development.
We’ve just uploaded mypy 1.10 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 onRead the Docs.
Mypy now supportsTypeIs (PEP 742), which allowsfunctions to narrow the type of a value, similar toisinstance(). UnlikeTypeGuard,TypeIs can narrow in both theif andelse branches of an if statement:
fromtyping_extensionsimportTypeIsdefis_str(s:object)->TypeIs[str]:returnisinstance(s,str)deff(o:str|int)->None:ifis_str(o):# Type of o is 'str'...else:# Type of o is 'int'...
TypeIs will be added to thetyping module in Python 3.13, but itcan be used on earlier Python versions by importing it fromtyping_extensions.
This feature was contributed by Jelle Zijlstra (PR16898).
PEP 696 adds support for type parameter defaults.Example:
fromtypingimportGenericfromtyping_extensionsimportTypeVarT=TypeVar("T",default=int)classC(Generic[T]):...x:C=...y:C[str]=...reveal_type(x)# C[int], because of the defaultreveal_type(y)# C[str]
TypeVar defaults will be added to thetyping module in Python 3.13, but theycan be used with earlier Python releases by importingTypeVar fromtyping_extensions.
This feature was contributed by Marc Mueller (PR16878and PR16925).
As part of the initial steps towards implementingPEP 695, mypy now supportsTypeAliasType.TypeAliasType provides a backport of the newtype statement in Python 3.12.
typeListOrSet[T]=list[T]|set[T]
is equivalent to:
T=TypeVar("T")ListOrSet=TypeAliasType("ListOrSet",list[T]|set[T],type_params=(T,))
Example of use in mypy:
fromtyping_extensionsimportTypeAliasType,TypeVarNewUnionType=TypeAliasType("NewUnionType",int|str)x:NewUnionType=42y:NewUnionType='a'z:NewUnionType=object()# error: Incompatible types in assignment (expression has type "object", variable has type "int | str") [assignment]T=TypeVar("T")ListOrSet=TypeAliasType("ListOrSet",list[T]|set[T],type_params=(T,))a:ListOrSet[int]=[1,2]b:ListOrSet[str]={'a','b'}c:ListOrSet[str]='test'# error: Incompatible types in assignment (expression has type "str", variable has type "list[str] | set[str]") [assignment]
TypeAliasType was added to thetyping module in Python 3.12, but it can be used with earlier Python releases by importing fromtyping_extensions.
This feature was contributed by Ali Hamdan (PR16926, PR17038 and PR17053)
Mypy will reject unsafe uses ofsuper() more consistently, when the target has atrivial (empty) body. Example:
classProto(Protocol):defmethod(self)->int:...classSub(Proto):defmethod(self)->int:returnsuper().meth()# Error (unsafe)
This feature was contributed by Shantanu (PR16756).
Provide an easier way to define IR-to-IR transforms (Jukka Lehtosalo, PR16998)
Implement lowering pass and add primitives for int (in)equality (Jukka Lehtosalo, PR17027)
Implement lowering for remaining tagged integer comparisons (Jukka Lehtosalo, PR17040)
Optimize away some bool/bit registers (Jukka Lehtosalo, PR17022)
Remangle redefined names produced by async with (Richard Si, PR16408)
Optimize TYPE_CHECKING to False at Runtime (Srinivas Lade, PR16263)
Fix compilation of unreachable comprehensions (Richard Si, PR15721)
Don’t crash on non-inlinable final local reads (Richard Si, PR15719)
Use lower-case generics more consistently in error messages (Jukka Lehtosalo, PR17035)
Fix incorrect inferred type when accessing descriptor on union type (Matthieu Devlin, PR16604)
Fix crash when expanding invalidUnpack in aCallable alias (Ali Hamdan, PR17028)
Fix false positive when string formatting with string enum (roberfi, PR16555)
Narrow individual items when matching a tuple to a sequence pattern (Loïc Simon, PR16905)
Fix false positive from type variable within TypeGuard or TypeIs (Evgeniy Slobodkin, PR17071)
Improveyieldfrom inference for unions of generators (Shantanu, PR16717)
Fix emulating hash method logic inattrs classes (Hashem, PR17016)
Add reverted typeshed commit that usesParamSpec forfunctools.wraps (Tamir Duberstein, PR16942)
Fix type narrowing fortypes.EllipsisType (Shantanu, PR17003)
Fix single item enum match type exhaustion (Oskari Lehto, PR16966)
Improve type inference with empty collections (Marc Mueller, PR16994)
Fix override checking for decorated property (Shantanu, PR16856)
Fix narrowing on match with function subject (Edward Paget, PR16503)
Allow+N withinLiteral[...] (Spencer Brown, PR16910)
Experimental: Support TypedDict withintype[...] (Marc Mueller, PR16963)
Experimtental: Fix issue with TypedDict with optional keys intype[...] (Marc Mueller, PR17068)
Please seegit log for full list of standard library typeshed stub changes.
Fix error reporting on cached run after uninstallation of third party library (Shantanu, PR17420)
Thanks to all mypy contributors who contributed to this release:
Alex Waygood
Ali Hamdan
Edward Paget
Evgeniy Slobodkin
Hashem
hesam
Hugo van Kemenade
Ihor
James Braza
Jelle Zijlstra
jhance
Jukka Lehtosalo
Loïc Simon
Marc Mueller
Matthieu Devlin
Michael R. Crusoe
Nikita Sobolev
Oskari Lehto
Riccardo Di Maio
Richard Si
roberfi
Roman Solomatin
Sam Xifaras
Shantanu
Spencer Brown
Srinivas Lade
Tamir Duberstein
youkaichao
I’d also like to thank my employer, Dropbox, for supporting mypy development.
We’ve just uploaded mypy 1.9 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 onRead the Docs.
Because the version of typeshed we use in mypy 1.9 doesn’t support 3.7, neither does mypy 1.9. (Jared Hance, PR16883)
We are planning to enablelocal partial types (enabled via the--local-partial-types flag) later this year by default. This changewas announced years ago, but now it’s finally happening. This is amajor backward-incompatible change, so we’ll probably include it aspart of the upcoming mypy 2.0 release. This makes daemon andnon-daemon mypy runs have the same behavior by default.
Local partial types can also be enabled in the mypy config file:
local_partial_types=True
We are looking at providing a tool to make it easier to migrateprojects to use--local-partial-types, but it’s not yet clear whetherthis is practical. The migration usually involves adding someexplicit type annotations to module-level and class-level variables.
This release contains new experimental support for type parameterdefaults (PEP 696). Please try itout! This feature was contributed by Marc Mueller.
Since this feature will be officially introduced in the next Pythonfeature release (3.13), you will need to importTypeVar,ParamSpecorTypeVarTuple fromtyping_extensions to use defaults for now.
This example adapted from the PEP defines a default forBotT:
fromtypingimportGenericfromtyping_extensionsimportTypeVarclassBot:...BotT=TypeVar("BotT",bound=Bot,default=Bot)classContext(Generic[BotT]):bot:BotTclassMyBot(Bot):...# type is Bot (the default)reveal_type(Context().bot)# type is MyBotreveal_type(Context[MyBot]().bot)
Fix missing type store for overloads (Marc Mueller, PR16803)
Fix'WriteToConn'objecthasnoattribute'flush' (Charlie Denton, PR16801)
Improve TypeAlias error messages (Marc Mueller, PR16831)
Support narrowing unions that includetype[None] (Christoph Tyralla, PR16315)
Support TypedDict functional syntax as class base type (anniel-stripe, PR16703)
Accept multiline quoted annotations (Shantanu, PR16765)
Allow unary + inLiteral (Jelle Zijlstra, PR16729)
Substitute type variables in return type of static methods (Kouroche Bouchiat, PR16670)
Consider TypeVarTuple to be invariant (Marc Mueller, PR16759)
Addalias support tofield() inattrs plugin (Nikita Sobolev, PR16610)
Improve attrs hashability detection (Tin Tvrtković, PR16556)
Speed up finding function type variables (Jukka Lehtosalo, PR16562)
Document supported values for--enable-incomplete-feature in “mypy –help” (Froger David, PR16661)
Update new type system discussion links (thomaswhaley, PR16841)
Add missing class instantiation to cheat sheet (Aleksi Tarvainen, PR16817)
Document how evil--no-strict-optional is (Shantanu, PR16731)
Improve mypy daemon documentation note about local partial types (Makonnen Makonnen, PR16782)
Fix numbering error (Stefanie Molin, PR16838)
Various documentation improvements (Shantanu, PR16836)
Ignore private function/method parameters when they are missing from the stub (private parameter names start with a single underscore and have a default) (PR16507)
Ignore a new protocol dunder (Alex Waygood, PR16895)
Private parameters can be omitted (Sebastian Rittau, PR16507)
Add support for setting enum members to “…” (Jelle Zijlstra, PR16807)
Adjust symbol table logic (Shantanu, PR16823)
Fix posisitional-only handling in overload resolution (Shantanu, PR16750)
Thanks to all mypy contributors who contributed to this release:
Aleksi Tarvainen
Alex Waygood
Ali Hamdan
anniel-stripe
Charlie Denton
Christoph Tyralla
Dheeraj
Fabian Keller
Fabian Lewis
Froger David
Ihor
Jared Hance
Jelle Zijlstra
Jukka Lehtosalo
Kouroche Bouchiat
Lukas Geiger
Maarten Huijsmans
Makonnen Makonnen
Marc Mueller
Nikita Sobolev
Sebastian Rittau
Shantanu
Stefanie Molin
Stephen Morton
thomaswhaley
Tin Tvrtković
WeilerMarcel
Wesley Collin Wright
zipperer
I’d also like to thank my employer, Dropbox, for supporting mypy development.
We’ve just uploaded mypy 1.8 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 onRead the Docs.
Do not intersect types in isinstance checks if at least one is final (Christoph Tyralla, PR16330)
Detect that@final class without__bool__ cannot have falsey instances (Ilya Priven, PR16566)
Do not allowTypedDict classes with extra keywords (Nikita Sobolev, PR16438)
Do not allow class-level keywords forNamedTuple (Nikita Sobolev, PR16526)
Make imprecise constraints handling more robust (Ivan Levkivskyi, PR16502)
Fix strict-optional in extending generic TypedDict (Ivan Levkivskyi, PR16398)
Allow type ignores of PEP 695 constructs (Shantanu, PR16608)
Enabletype_check_only support forTypedDict andNamedTuple (Nikita Sobolev, PR16469)
Add fast path to analyzing special form assignments (Jukka Lehtosalo, PR16561)
Improve handling of unrepresentable defaults (Jelle Zijlstra, PR16433)
Print more helpful errors if a function is missing from stub (Alex Waygood, PR16517)
Support@type_check_only decorator (Nikita Sobolev, PR16422)
Warn about missing__del__ (Shantanu, PR16456)
Fix crashes with some uses offinal anddeprecated (Shantanu, PR16457)
Allow mypy to output a junit file with per-file results (Matthew Wright, PR16388)
Please seegit log for full list of standard library typeshed stub changes.
Thanks to all mypy contributors who contributed to this release:
Alex Waygood
Ali Hamdan
Chad Dombrova
Christoph Tyralla
Ilya Priven
Ivan Levkivskyi
Jelle Zijlstra
Jukka Lehtosalo
Marcel Telka
Matthew Wright
Michael R. Crusoe
Nikita Sobolev
Ole Peder Brandtzæg
robjhornby
Shantanu
Sveinung Gundersen
Valentin Stanciu
I’d also like to thank my employer, Dropbox, for supporting mypy development.
Posted by Wesley Collin Wright
We’ve just uploaded mypy 1.7 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 onRead the Docs.
**kwargs Typing¶Mypy now has support for usingUnpack[...] with a TypedDict type to annotate**kwargs arguments enabled by default. Example:
# Or 'from typing_extensions import ...'fromtypingimportTypedDict,UnpackclassPerson(TypedDict):name:strage:intdeffoo(**kwargs:Unpack[Person])->None:...foo(name="x",age=1)# Okfoo(name=1)# Error
The definition offoo above is equivalent to the one below, with keyword-only argumentsname andage:
deffoo(*,name:str,age:int)->None:...
Refer toPEP 692 for more information. Note that unlike in the current version of the PEP, mypy always treats signatures withUnpack[SomeTypedDict] as equivalent to their expanded forms with explicit keyword arguments, and there aren’t special type checking rules for TypedDict arguments.
This was contributed by Ivan Levkivskyi back in 2022 (PR13471).
Mypy now has support for variadic generics (TypeVarTuple) enabled by default, as an experimental feature. Refer toPEP 646 for the details.
TypeVarTuple was implemented by Jared Hance and Ivan Levkivskyi over several mypy releases, with help from Jukka Lehtosalo.
Changes included in this release:
Fix handling of tuple type context with unpacks (Ivan Levkivskyi, PR16444)
Handle TypeVarTuples when checking overload constraints (robjhornby, PR16428)
Enable Unpack/TypeVarTuple support (Ivan Levkivskyi, PR16354)
Fix crash on unpack call special-casing (Ivan Levkivskyi, PR16381)
Some final touches for variadic types support (Ivan Levkivskyi, PR16334)
Support PEP-646 and PEP-692 in the same callable (Ivan Levkivskyi, PR16294)
Support new* syntax for variadic types (Ivan Levkivskyi, PR16242)
Correctly handle variadic instances with empty arguments (Ivan Levkivskyi, PR16238)
Correctly handle runtime type applications of variadic types (Ivan Levkivskyi, PR16240)
Support variadic tuple packing/unpacking (Ivan Levkivskyi, PR16205)
Better support for variadic calls and indexing (Ivan Levkivskyi, PR16131)
Subtyping and inference of user-defined variadic types (Ivan Levkivskyi, PR16076)
Complete type analysis of variadic types (Ivan Levkivskyi, PR15991)
If you want to install package dependencies needed by mypyc (not just mypy), you should now installmypy[mypyc] instead of justmypy:
python3-mpipinstall-U'mypy[mypyc]'
Mypy has many more users than mypyc, so always installing mypyc dependencies would often bring unnecessary dependencies.
This change was contributed by Shantanu (PR16229).
Mypy no longer considers an import such asimporta.basb as an explicit re-export. The old behavior was arguably inconsistent and surprising. This may impact some stub packages, such as older versions oftypes-six. You can change the import tofromaimportbasb, if treating the import as a re-export was intentional.
This change was contributed by Anders Kaseorg (PR14086).
The new type inference algorithm that was recently introduced to mypy (but was not enabled by default) is now enabled by default. It improves type inference of calls to generic callables where an argument is also a generic callable, in particular. You can use--old-type-inference to disable the new behavior.
The new algorithm can (rarely) produce different error messages, different error codes, or errors reported on different lines. This is more likely in cases where generic types were used incorrectly.
The new type inference algorithm was contributed by Ivan Levkivskyi. PR16345 enabled it by default.
Mypy now can narrow tuple types usinglen() checks. Example:
deff(t:tuple[int,int]|tuple[int,int,int])->None:iflen(t)==2:a,b=t# Ok...
This feature was contributed by Ivan Levkivskyi (PR16237).
Mypy supports experimental, more precise checking of tuple type lengths through--enable-incomplete-feature=PreciseTupleTypes. Refer to thedocumentation for more information.
More generally, we are planning to use--enable-incomplete-feature to introduce experimental features that would benefit from community feedback.
This feature was contributed by Ivan Levkivskyi (PR16237).
We now maintain achangelog in the mypy Git repository. It mirrors the contents ofmypy release blog posts. We will continue to also publish release blog posts. In the future, release blog posts will be created based on the changelog near a release date.
This was contributed by Shantanu (PR16280).
Fix daemon crash caused by deleted submodule (Jukka Lehtosalo, PR16370)
Fix file reloading in dmypy with –export-types (Ivan Levkivskyi, PR16359)
Fix dmypy inspect on Windows (Ivan Levkivskyi, PR16355)
Fix dmypy inspect for namespace packages (Ivan Levkivskyi, PR16357)
Fix return type change to optional in generic function (Jukka Lehtosalo, PR16342)
Fix daemon false positives related to module-level__getattr__ (Jukka Lehtosalo, PR16292)
Fix daemon crash related to ABCs (Jukka Lehtosalo, PR16275)
Stream dmypy output instead of dumping everything at the end (Valentin Stanciu, PR16252)
Make sure all dmypy errors are shown (Valentin Stanciu, PR16250)
Generate error on duplicate function definitions (Jukka Lehtosalo, PR16309)
Don’t crash on unreachable statements (Jukka Lehtosalo, PR16311)
Avoid cyclic reference in nested functions (Jukka Lehtosalo, PR16268)
Fix direct__dict__ access on inner functions in new Python (Shantanu, PR16084)
Make tuple packing and unpacking more efficient (Jukka Lehtosalo, PR16022)
Update starred expression error message to match CPython (Cibin Mathew, PR16304)
Fix error code of “Maybe you forgot to use await” note (Jelle Zijlstra, PR16203)
Use error code[unsafe-overload] for unsafe overloads, instead of[misc] (Randolf Scholz, PR16061)
Reword the error message related to void functions (Albert Tugushev, PR15876)
Represent bottom type as Never in messages (Shantanu, PR15996)
Add hint for AsyncIterator incompatible return type (Ilya Priven, PR15883)
Don’t suggest stubs packages where the runtime package now ships with types (Alex Waygood, PR16226)
dataclass.replace: Allow transformed classes (Ilya Priven, PR15915)
dataclass.replace: Fall through to typeshed signature (Ilya Priven, PR15962)
Documentdataclass_transform behavior (Ilya Priven, PR16017)
attrs: Remove fields type check (Ilya Priven, PR15983)
attrs,dataclasses: Don’t enforce slots when base class doesn’t (Ilya Priven, PR15976)
Fix crash on dataclass field / property collision (Nikita Sobolev, PR16147)
Write stubs with utf-8 encoding (Jørgen Lind, PR16329)
Fix missing property setter in semantic analysis mode (Ali Hamdan, PR16303)
Unify C extension and pure python stub generators with object oriented design (Chad Dombrova, PR15770)
Multiple fixes to the generated imports (Ali Hamdan, PR15624)
Generate valid dataclass stubs (Ali Hamdan, PR15625)
Fix incremental mode crash on TypedDict in method (Ivan Levkivskyi, PR16364)
Fix crash on star unpack in TypedDict (Ivan Levkivskyi, PR16116)
Fix crash on malformed TypedDict in incremental mode (Ivan Levkivskyi, PR16115)
Fix crash with report generation on namespace packages (Shantanu, PR16019)
Fix crash when parsing error code config with typo (Shantanu, PR16005)
Fix__post_init__() internal error (Ilya Priven, PR16080)
Make it easier to copy commands from README (Hamir Mahal, PR16133)
Document and rename[overload-overlap] error code (Shantanu, PR16074)
Document--force-uppercase-builtins and--force-union-syntax (Nikita Sobolev, PR16049)
Documentforce_union_syntax andforce_uppercase_builtins (Nikita Sobolev, PR16048)
Document we’re not tracking relationships between symbols (Ilya Priven, PR16018)
Propagate narrowed types to lambda expressions (Ivan Levkivskyi, PR16407)
Avoid importing fromsetuptools._distutils (Shantanu, PR16348)
Delete recursive aliases flags (Ivan Levkivskyi, PR16346)
Properly use proper subtyping for callables (Ivan Levkivskyi, PR16343)
Use upper bound as inference fallback more consistently (Ivan Levkivskyi, PR16344)
Add[unimported-reveal] error code (Nikita Sobolev, PR16271)
Add|= and| operators support forTypedDict (Nikita Sobolev, PR16249)
Clarify variance convention for Parameters (Ivan Levkivskyi, PR16302)
Correctly recognizetyping_extensions.NewType (Ganden Schaffner, PR16298)
Fix partially defined in the case of missing type maps (Shantanu, PR15995)
Use SPDX license identifier (Nikita Sobolev, PR16230)
Make__qualname__ and__module__ available in class bodies (Anthony Sottile, PR16215)
stubtest: Hint when args in stub need to be keyword-only (Alex Waygood, PR16210)
Tuple slice should not propagate fallback (Thomas Grainger, PR16154)
Fix cases of type object handling for overloads (Shantanu, PR16168)
Fix walrus interaction with empty collections (Ivan Levkivskyi, PR16197)
Use type variable bound when it appears as actual during inference (Ivan Levkivskyi, PR16178)
Use upper bounds as fallback solutions for inference (Ivan Levkivskyi, PR16184)
Special-case type inference of empty collections (Ivan Levkivskyi, PR16122)
Allow TypedDict unpacking in Callable types (Ivan Levkivskyi, PR16083)
Fix inference for overloaded__call__ with generic self (Shantanu, PR16053)
Call dynamic class hook on generic classes (Petter Friberg, PR16052)
Preserve implicitly exported types via attribute access (Shantanu, PR16129)
Fix a stubtest bug (Alex Waygood)
Fixtuple[Any,...] subtyping (Shantanu, PR16108)
Lenient handling of trivial Callable suffixes (Ivan Levkivskyi, PR15913)
Addadd_overloaded_method_to_class helper for plugins (Nikita Sobolev, PR16038)
Bundlemisc/proper_plugin.py as a part ofmypy (Nikita Sobolev, PR16036)
FixcaseAny() in match statement (DS/Charlie, PR14479)
Make iterable logic more consistent (Shantanu, PR16006)
Fix inference for properties with__call__ (Shantanu, PR15926)
Please seegit log for full list of standard library typeshed stub changes.
Thanks to all mypy contributors who contributed to this release:
Albert Tugushev
Alex Waygood
Ali Hamdan
Anders Kaseorg
Anthony Sottile
Chad Dombrova
Cibin Mathew
dinaldoap
DS/Charlie
Eli Schwartz
Ganden Schaffner
Hamir Mahal
Ihor
Ikko Eltociear Ashimine
Ilya Priven
Ivan Levkivskyi
Jelle Zijlstra
Jukka Lehtosalo
Jørgen Lind
KotlinIsland
Matt Bogosian
Nikita Sobolev
Petter Friberg
Randolf Scholz
Shantanu
Thomas Grainger
Valentin Stanciu
I’d also like to thank my employer, Dropbox, for supporting mypy development.
Posted by Jukka Lehtosalo
We’ve just uploaded mypy 1.6 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 onRead the Docs.
Mypy now uses the error code import-untyped if an import targets an installed library that doesn’t support static type checking, and no stub files are available. Other invalid imports produce the import-not-found error code. They both are subcodes of the import error code, which was previously used for both kinds of import-related errors.
Use –disable-error-code=import-untyped to only ignore import errors about installed libraries without stubs. This way mypy will still report errors about typos in import statements, for example.
If you use –warn-unused-ignore or –strict, mypy will complain if you use # type: ignore[import] to ignore an import error. You are expected to use one of the more specific error codes instead. Otherwise, ignoring the import error code continues to silence both errors.
This feature was contributed by Shantanu (PR15840, PR14740).
Running mypy with –python-version 3.6, for example, is no longer supported. Python 3.6 hasn’t been properly supported by mypy for some time now, and this makes it explicit. This was contributed by Nikita Sobolev (PR15668).
Using –disallow-untyped-calls could be annoying when using libraries with missing type information, as mypy would generate many errors about code that uses the library. Now you can use –untyped-calls-exclude=acme, for example, to disable these errors about calls targeting functions defined in the acme package. Refer to thedocumentation for more information.
This feature was contributed by Ivan Levkivskyi (PR15845).
Mypy now does a better job inferring type variables inside arguments of callable types. For example, this code fragment now type checks correctly:
deff(c:Callable[[T,S],None])->Callable[[str,T,S],None]:...defg(*x:int)->None:...reveal_type(f(g))# Callable[[str, int, int], None]
This was contributed by Ivan Levkivskyi (PR15910).
Mypy now doesn’t consider an overload item with an argument type None to overlap with a type variable:
@overloaddeff(x:None)->None:..@overloaddeff(x:T)->Foo[T]:......
Previously mypy would generate an error about the definition of f above. This is slightly unsafe if the upper bound of T is object, since the value of the type variable could be None. We relaxed the rules a little, since this solves a common issue.
This feature was contributed by Ivan Levkivskyi (PR15846).
The experimental new type inference algorithm (polymorphic inference) introduced as an opt-in feature in mypy 1.5 has several improvements:
Improve transitive closure computation during constraint solving (Ivan Levkivskyi, PR15754)
Add support for upper bounds and values with –new-type-inference (Ivan Levkivskyi, PR15813)
Basic support for variadic types with –new-type-inference (Ivan Levkivskyi, PR15879)
Polymorphic inference: support for parameter specifications and lambdas (Ivan Levkivskyi, PR15837)
Invalidate cache when adding –new-type-inference (Marc Mueller, PR16059)
Note: We are planning to enable –new-type-inference by default in mypy 1.7. Please try this out and let us know if you encounter any issues.
Support self-types containing ParamSpec (Ivan Levkivskyi, PR15903)
Allow “…” in Concatenate, and clean up ParamSpec literals (Ivan Levkivskyi, PR15905)
Fix ParamSpec inference for callback protocols (Ivan Levkivskyi, PR15986)
Infer ParamSpec constraint from arguments (Ivan Levkivskyi, PR15896)
Fix crash on invalid type variable with ParamSpec (Ivan Levkivskyi, PR15953)
Fix subtyping between ParamSpecs (Ivan Levkivskyi, PR15892)
Fix __mypy-replace false positives (Alex Waygood, PR15689)
Fix edge case for bytes enum subclasses (Alex Waygood, PR15943)
Generate error if typeshed is missing modules from the stdlib (Alex Waygood, PR15729)
Fixes to new check for missing stdlib modules (Alex Waygood, PR15960)
Fix stubtest enum.Flag edge case (Alex Waygood, PR15933)
Make unsupported PEP 695 features (introduced in Python 3.12) give a reasonable error message (Shantanu, PR16013)
Remove the –py2 command-line argument (Marc Mueller, PR15670)
Change empty tuple from tuple[] to tuple[()] in error messages (Nikita Sobolev, PR15783)
Fix assert_type failures when some nodes are deferred (Nikita Sobolev, PR15920)
Generate error on unbound TypeVar with values (Nikita Sobolev, PR15732)
Fix over-eager types-google-cloud-ndb suggestion (Shantanu, PR15347)
Fix type narrowing of == None and in (None,) conditions (Marti Raudsepp, PR15760)
Fix inference for attrs.fields (Shantanu, PR15688)
Make “await in non-async function” a non-blocking error and give it an error code (Gregory Santosa, PR15384)
Add basic support for decorated overloads (Ivan Levkivskyi, PR15898)
Fix TypeVar regression with self types (Ivan Levkivskyi, PR15945)
Add __match_args__ to dataclasses with no fields (Ali Hamdan, PR15749)
Include stdout and stderr in dmypy verbose output (Valentin Stanciu, PR15881)
Improve match narrowing and reachability analysis (Shantanu, PR15882)
Support __bool__ with Literal in –warn-unreachable (Jannic Warken, PR15645)
Fix inheriting from generic @frozen attrs class (Ilya Priven, PR15700)
Correctly narrow types for tuple[type[X], …] (Nikita Sobolev, PR15691)
Don’t flag intentionally empty generators unreachable (Ilya Priven, PR15722)
Add tox.ini to mypy sdist (Marcel Telka, PR15853)
Fix mypyc regression with pretty (Shantanu, PR16124)
Typeshed is now modular and distributed as separate PyPI packages for everything except the standard library stubs. Please seegit log for full list of typeshed changes.
Thanks to Max Murin, who did most of the release manager work for this release (I just did the final steps).
Thanks to all mypy contributors who contributed to this release:
Albert Tugushev
Alex Waygood
Ali Hamdan
chylek
EXPLOSION
Gregory Santosa
Ilya Priven
Ivan Levkivskyi
Jannic Warken
KotlinIsland
Marc Mueller
Marcel Johannesmann
Marcel Telka
Mark Byrne
Marti Raudsepp
Max Murin
Nikita Sobolev
Shantanu
Valentin Stanciu
Posted by Jukka Lehtosalo
We’ve just uploaded mypy 1.5 to the Python Package Index (PyPI). Mypy is a static type checker for Python. This release includes new features, deprecations and bug fixes. You can install it as follows:
python3 -m pip install -U mypy
You can read the full documentation for this release onRead the Docs.
Mypy no longer supports running with Python 3.7, which has reached end-of-life. This was contributed by Shantanu (PR15566).
If you enable the explicit-override error code, mypy will generate an error if a method override doesn’t use the @typing.override decorator (as discussed inPEP 698). This way mypy will detect accidentally introduced overrides. Example:
# mypy: enable-error-code="explicit-override"fromtyping_extensionsimportoverrideclassC:deffoo(self)->None:passdefbar(self)->None:passclassD(C):# Error: Method "foo" is not using @override but is# overriding a methoddeffoo(self)->None:...@overridedefbar(self)->None:# OK...
You can enable the error code via –enable-error-code=explicit-override on the mypy command line or enable_error_code = explicit-override in the mypy config file.
The override decorator will be available in typing in Python 3.12, but you can also use the backport from a recent version oftyping_extensions on all supported Python versions.
This feature was contributed by Marc Mueller(PR15512).
Mypy was previously overly strict when type checking TypedDict creation and update operations. Though these checks were often technically correct, they sometimes triggered for apparently valid code. These checks have now been relaxed by default. You can enable stricter checking by using the new –extra-checks flag.
Construction using the** syntax is now more flexible:
fromtypingimportTypedDictclassA(TypedDict):foo:intbar:intclassB(TypedDict):foo:inta:A={"foo":1,"bar":2}b:B={"foo":3}a2:A={**a,**b}# OK (previously an error)
You can also call update() with a TypedDict argument that contains a subset of the keys in the updated TypedDict:
a.update(b)# OK (previously an error)
This feature was contributed by Ivan Levkivskyi (PR15425).
The behavior of –strict-concatenate is now included in the new –extra-checks flag, and the old flag is deprecated.
If you use –show-error-code-links, mypy will add documentation links to (many) reported errors. The links are not shown for error messages that are sufficiently obvious, and they are shown once per error code only.
Example output:
a.py:1:error:Needtypeannotationfor"foo"(hint:"x: List[<type>] = ...")[var-annotated]a.py:1:note:Seehttps://mypy.rtfd.io/en/stable/_refs.html#code-var-annotated for more info
This was contributed by Ivan Levkivskyi (PR15449).
If a module top level has unreachable code, mypy won’t type check the unreachable statements. This is consistent with how functions behave. The behavior of –warn-unreachable is also more consistent now.
This was contributed by Ilya Priven (PR15386).
You can use –new-type-inference to opt into an experimental new type inference algorithm. It fixes issues when calling a generic functions with an argument that is also a generic function, in particular. This current implementation is still incomplete, but we encourage trying it out and reporting bugs if you encounter regressions. We are planning to enable the new algorithm by default in a future mypy release.
This feature was contributed by Ivan Levkivskyi (PR15287).
Mypy and mypyc now support running on recent Python 3.12 development versions. Not all new Python 3.12 features are supported, and we don’t ship compiled wheels for Python 3.12 yet.
Fix ast warnings for Python 3.12 (Nikita Sobolev, PR15558)
mypyc: Fix multiple inheritance with a protocol on Python 3.12 (Jukka Lehtosalo, PR15572)
mypyc: Fix self-compilation on Python 3.12 (Jukka Lehtosalo, PR15582)
mypyc: Fix 3.12 issue with pickling of instances with __dict__ (Jukka Lehtosalo, PR15574)
mypyc: Fix i16 on Python 3.12 (Jukka Lehtosalo, PR15510)
mypyc: Fix int operations on Python 3.12 (Jukka Lehtosalo, PR15470)
mypyc: Fix generators on Python 3.12 (Jukka Lehtosalo, PR15472)
mypyc: Fix classes with __dict__ on 3.12 (Jukka Lehtosalo, PR15471)
mypyc: Fix coroutines on Python 3.12 (Jukka Lehtosalo, PR15469)
mypyc: Don’t use _PyErr_ChainExceptions on 3.12, since it’s deprecated (Jukka Lehtosalo, PR15468)
mypyc: Add Python 3.12 feature macro (Jukka Lehtosalo, PR15465)
Improve signature of dataclasses.replace (Ilya Priven, PR14849)
Fix dataclass/protocol crash on joining types (Ilya Priven, PR15629)
Fix strict optional handling in dataclasses (Ivan Levkivskyi, PR15571)
Support optional types for custom dataclass descriptors (Marc Mueller, PR15628)
Add__slots__ attribute to dataclasses (Nikita Sobolev, PR15649)
Support better __post_init__ method signature for dataclasses (Nikita Sobolev, PR15503)
Support unsigned 8-bit native integer type: mypy_extensions.u8 (Jukka Lehtosalo, PR15564)
Support signed 16-bit native integer type: mypy_extensions.i16 (Jukka Lehtosalo, PR15464)
Define mypy_extensions.i16 in stubs (Jukka Lehtosalo, PR15562)
Document more unsupported features and update supported features (Richard Si, PR15524)
Fix final NamedTuple classes (Richard Si, PR15513)
Use C99 compound literals for undefined tuple values (Jukka Lehtosalo, PR15453)
Don’t explicitly assign NULL values in setup functions (Logan Hunt, PR15379)
Constant fold additional unary and binary expressions (Richard Si, PR15202)
Exclude the same special attributes from Protocol as CPython (Kyle Benesch, PR15490)
Change the default value of the slots argument of attrs.define to True, to match runtime behavior (Ilya Priven, PR15642)
Fix type of class attribute if attribute is defined in both class and metaclass (Alex Waygood, PR14988)
Handle type the same as typing.Type in the first argument of classmethods (Erik Kemperman, PR15297)
Fix –find-occurrences flag (Shantanu, PR15528)
Fix error location for class patterns (Nikita Sobolev, PR15506)
Fix re-added file with errors in mypy daemon (Ivan Levkivskyi, PR15440)
Fix dmypy run on Windows (Ivan Levkivskyi, PR15429)
Fix abstract and non-abstract variant error for property deleter (Shantanu, PR15395)
Remove special casing for “cannot” in error messages (Ilya Priven, PR15428)
Add runtime__slots__ attribute to attrs classes (Nikita Sobolev, PR15651)
Add get_expression_type to CheckerPluginInterface (Ilya Priven, PR15369)
Remove parameters that no longer exist from NamedTuple._make() (Alex Waygood, PR15578)
Allow using typing.Self in__all__ with an explicit @staticmethod decorator (Erik Kemperman, PR15353)
Fix self types in subclass methods without Self annotation (Ivan Levkivskyi, PR15541)
Check for abstract class objects in tuples (Nikita Sobolev, PR15366)
Typeshed is now modular and distributed as separate PyPI packages for everything except the standard library stubs. Please seegit log for full list of typeshed changes.
Thanks to all mypy contributors who contributed to this release:
Adel Atallah
Alex Waygood
Ali Hamdan
Erik Kemperman
Federico Padua
Ilya Priven
Ivan Levkivskyi
Jelle Zijlstra
Jared Hance
Jukka Lehtosalo
Kyle Benesch
Logan Hunt
Marc Mueller
Nikita Sobolev
Richard Si
Shantanu
Stavros Ntentos
Valentin Stanciu
Posted by Valentin Stanciu
We’ve just uploaded mypy 1.4 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 onRead the Docs.
Mypy can now ensure that when renaming a method, overrides are also renamed. You can explicitly mark a method as overriding a base class method by using the @typing.override decorator (PEP 698). If the method is then renamed in the base class while the method override is not, mypy will generate an error. The decorator will be available in typing in Python 3.12, but you can also use the backport from a recent version oftyping_extensions on all supported Python versions.
This feature was contributed byThomas M Kehrenberg (PR14609).
Previously, type narrowing was not propagated to nested functions because it would not be sound if the narrowed variable changed between the definition of the nested function and the call site. Mypy will now propagate the narrowed type if the variable is not assigned to after the definition of the nested function:
defouter(x:str|None=None)->None:ifxisNone:x=calculate_default()reveal_type(x)# "str" (narrowed)defnested()->None:reveal_type(x)# Now "str" (used to be "str | None")nested()
This may generate some new errors because asserts that were previously necessary may become tautological or no-ops.
This was contributed by Jukka Lehtosalo (PR15133).
Mypy now allows narrowing enum types using the == operator. Previously this was only supported when using the is operator. This makes exhaustiveness checking with enum types more usable, as the requirement to use the is operator was not very intuitive. In this example mypy can detect that the developer forgot to handle the value MyEnum.C in example
fromenumimportEnumclassMyEnum(Enum):A=0B=1C=2defexample(e:MyEnum)->str:# Error: Missing return statementife==MyEnum.A:return'x'elife==MyEnum.B:return'y'
Adding an extra elif case resolves the error:
...defexample(e:MyEnum)->str:# No error -- all values coveredife==MyEnum.A:return'x'elife==MyEnum.B:return'y'elife==MyEnum.C:return'z'
This change can cause false positives in test cases that have assert statements like assert o.x == SomeEnum.X when using –strict-equality. Example:
# mypy: strict-equalityfromenumimportEnumclassMyEnum(Enum):A=0B=1classC:x:MyEnum...deftest_something()->None:c=C(...)assertc.x==MyEnum.Ac.do_something_that_changes_x()assertc.x==MyEnum.B# Error: Non-overlapping equality check
These errors can be ignored using # type: ignore[comparison-overlap], or you can perform the assertion using a temporary variable as a workaround:
...deftest_something()->None:...x=c.xassertx==MyEnum.A# Does not narrow c.xc.do_something_that_changes_x()x=c.xassertx==MyEnum.B# OK
This feature was contributed by Shantanu (PR11521).
attrs.evolve: Support generics and unions (Ilya Konstantinov, PR15050)
Fix ctypes plugin (Alex Waygood)
Fix a crash when function-scope recursive alias appears as upper bound (Ivan Levkivskyi, PR15159)
Fix crash on follow_imports_for_stubs (Ivan Levkivskyi, PR15407)
Fix stubtest crash in explicit init subclass (Shantanu, PR15399)
Fix crash when indexing TypedDict with empty key (Shantanu, PR15392)
Fix crash on NamedTuple as attribute (Ivan Levkivskyi, PR15404)
Correctly track loop depth for nested functions/classes (Ivan Levkivskyi, PR15403)
Fix crash on joins with recursive tuples (Ivan Levkivskyi, PR15402)
Fix crash with custom ErrorCode subclasses (Marc Mueller, PR15327)
Fix crash in dataclass protocol with self attribute assignment (Ivan Levkivskyi, PR15157)
Fix crash on lambda in generic context with generic method in body (Ivan Levkivskyi, PR15155)
Fix recursive type alias crash in make_simplified_union (Ivan Levkivskyi, PR15216)
Use lower-case built-in collection types such as list[…] instead of List[…] in errors when targeting Python 3.9+ (Max Murin, PR15070)
Use X | Y union syntax in error messages when targeting Python 3.10+ (Omar Silva, PR15102)
Use type instead of Type in errors when targeting Python 3.9+ (Rohit Sanjay, PR15139)
Do not show unused-ignore errors in unreachable code, and make it a real error code (Ivan Levkivskyi, PR15164)
Don’t limit the number of errors shown by default (Rohit Sanjay, PR15138)
Improver message for truthy functions (madt2709, PR15193)
Output distinct types when type names are ambiguous (teresa0605, PR15184)
Update message about invalid exception type in try (AJ Rasmussen, PR15131)
Add explanation if argument type is incompatible because of an unsupported numbers type (Jukka Lehtosalo, PR15137)
Add more detail to ‘signature incompatible with supertype’ messages for non-callables (Ilya Priven, PR15263)
Add –local-partial-types note to dmypy docs (Alan Du, PR15259)
Update getting started docs for mypyc for Windows (Valentin Stanciu, PR15233)
Clarify usage of callables regarding type object in docs (Viicos, PR15079)
Clarify difference between disallow_untyped_defs and disallow_incomplete_defs (Ilya Priven, PR15247)
Use attrs and @attrs.define in documentation and tests (Ilya Priven, PR15152)
Do not remove Generic from base classes (Ali Hamdan, PR15316)
Support yield from statements (Ali Hamdan, PR15271)
Fix missing total from TypedDict class (Ali Hamdan, PR15208)
Fix call-based namedtuple omitted from class bases (Ali Hamdan, PR14680)
Support TypedDict alternative syntax (Ali Hamdan, PR14682)
Make stubgen respect MYPY_CACHE_DIR (Henrik Bäärnhielm, PR14722)
Fixes and simplifications (Ali Hamdan, PR15232)
Fix nested async functions when using TypeVar value restriction (Jukka Lehtosalo, PR14705)
Always allow returning Any from lambda (Ivan Levkivskyi, PR15413)
Add foundation for TypeVar defaults (PEP 696) (Marc Mueller, PR14872)
Update semantic analyzer for TypeVar defaults (PEP 696) (Marc Mueller, PR14873)
Make dict expression inference more consistent (Ivan Levkivskyi, PR15174)
Do not block on duplicate base classes (Nikita Sobolev, PR15367)
Generate an error when both staticmethod and classmethod decorators are used (Juhi Chandalia, PR15118)
Fix assert_type behaviour with literals (Carl Karsten, PR15123)
Fix match subject ignoring redefinitions (Vincent Vanlaer, PR15306)
Support__all__.remove (Shantanu, PR15279)
Typeshed is now modular and distributed as separate PyPI packages for everything except the standard library stubs. Please seegit log for full list of typeshed changes.
Thanks to all mypy contributors who contributed to this release:
Adrian Garcia Badaracco
AJ Rasmussen
Alan Du
Alex Waygood
Ali Hamdan
Carl Karsten
dosisod
Ethan Smith
Gregory Santosa
Heather White
Henrik Bäärnhielm
Ilya Konstantinov
Ilya Priven
Ivan Levkivskyi
Juhi Chandalia
Jukka Lehtosalo
Logan Hunt
madt2709
Marc Mueller
Max Murin
Nikita Sobolev
Omar Silva
Özgür
Richard Si
Rohit Sanjay
Shantanu
teresa0605
Thomas M Kehrenberg
Tin Tvrtković
Tushar Sadhwani
Valentin Stanciu
Viicos
Vincent Vanlaer
Wesley Collin Wright
William Santosa
yaegassy
I’d also like to thank my employer, Dropbox, for supporting mypy development.
Posted by Jared Hance
We’ve just uploaded mypy 1.3 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 onRead the Docs.
Stubtest: Check that the stub is abstract if the runtime is, even when the stub is an overloaded method (Alex Waygood, PR14955)
Stubtest: Verify stub methods or properties are decorated with @final if they are decorated with @final at runtime (Alex Waygood, PR14951)
Stubtest: Fix stubtest false positives with TypedDicts at runtime (Alex Waygood, PR14984)
Stubgen: Support @functools.cached_property (Nikita Sobolev, PR14981)
Improvements to stubgenc (Chad Dombrova, PR14564)
Improve async documentation (Shantanu, PR14973)
Improvements to cheat sheet (Shantanu, PR14972)
Add documentation for bytes formatting error code (Shantanu, PR14971)
Convert insecure links to use HTTPS (Marti Raudsepp, PR14974)
Also mention overloads in async iterator documentation (Shantanu, PR14998)
stubtest: Improve allowlist documentation (Shantanu, PR15008)
Clarify “Using types… but not at runtime” (Jon Shea, PR15029)
Fix alignment of cheat sheet example (Ondřej Cvacho, PR15039)
Fix error for callback protocol matching against callable type object (Shantanu, PR15042)
Improve bytes formatting error (Shantanu, PR14959)
Fix unions of bools and ints (Tomer Chachamu, PR15066)
Fix narrowing union types that include Self with isinstance (Christoph Tyralla, PR14923)
Allow objects matching SupportsKeysAndGetItem to be unpacked (Bryan Forbes, PR14990)
Check type guard validity for staticmethods (EXPLOSION, PR14953)
Fix sys.platform when cross-compiling with emscripten (Ethan Smith, PR14888)
Typeshed is now modular and distributed as separate PyPI packages for everything except the standard library stubs. Please seegit log for full list of typeshed changes.
Thanks to all mypy contributors who contributed to this release:
Alex Waygood
Amin Alaee
Bryan Forbes
Chad Dombrova
Charlie Denton
Christoph Tyralla
dosisod
Ethan Smith
EXPLOSION
Ilya Konstantinov
Ivan Levkivskyi
Jon Shea
Jukka Lehtosalo
KotlinIsland
Marti Raudsepp
Nikita Sobolev
Ondřej Cvacho
Shantanu
sobolevn
Tomer Chachamu
Yaroslav Halchenko
Posted by Wesley Collin Wright.
We’ve just uploaded mypy 1.2 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 onRead the Docs.
Support implicit default for “init” parameter in field specifiers (Wesley Collin Wright and Jukka Lehtosalo, PR15010)
Support descriptors in dataclass transform (Jukka Lehtosalo, PR15006)
Fix frozen_default in incremental mode (Wesley Collin Wright)
Fix frozen behavior for base classes with direct metaclasses (Wesley Collin Wright, PR14878)
Mypyc now uses a native, unboxed representation for values of type float. Previously these were heap-allocated Python objects. Native floats are faster and use less memory. Code that uses floating-point operations heavily can be several times faster when using native floats.
Various float operations and math functions also now have optimized implementations. Refer to thedocumentation for a full list.
This can change the behavior of existing code that uses subclasses of float. When assigning an instance of a subclass of float to a variable with the float type, it gets implicitly converted to a float instance when compiled:
fromlibimportMyFloat# MyFloat ia a subclass of "float"defexample()->None:x=MyFloat(1.5)y:float=x# Implicit conversion from MyFloat to floatprint(type(y))# float, not MyFloat
Previously, implicit conversions were applied to int subclasses but not float subclasses.
Also, int values can no longer be assigned to a variable with type float in compiled code, since these types now have incompatible representations. An explicit conversion is required:
defexample(n:int)->None:a:float=1# Error: cannot assign "int" to "float"b:float=1.0# OKc:float=n# Errord:float=float(n)# OK
This restriction only applies to assignments, since they could otherwise narrow down the type of a variable from float to int. int values can still be implicitly converted to float when passed as arguments to functions that expect float values.
Note that mypyc still doesn’t support arrays of unboxed float values. Using list[float] involves heap-allocated float objects, since list can only store boxed values. Support for efficient floating point arrays is one of the next major planned mypyc features.
Related changes:
Mypyc now supports signed 32-bit and 64-bit integer types in addition to the arbitrary-precision int type. You can use the types mypy_extensions.i32 and mypy_extensions.i64 to speed up code that uses integer operations heavily.
Simple example:
frommypy_extensionsimporti64definc(x:i64)->i64:returnx+1
Refer to thedocumentation for more information. This feature was contributed by Jukka Lehtosalo.
Multiple inheritance considers callable objects as subtypes of functions (Christoph Tyralla, PR14855)
stubtest: Respect @final runtime decorator and enforce it in stubs (Nikita Sobolev, PR14922)
Fix false positives related to type[
Fix duplication of ParamSpec prefixes and properly substitute ParamSpecs (EXPLOSION, PR14677)
Fix line number if__iter__ is incorrectly reported as missing (Jukka Lehtosalo, PR14893)
Fix incompatible overrides of overloaded generics with self types (Shantanu, PR14882)
Allow SupportsIndex in slice expressions (Shantanu, PR14738)
Support if statements in bodies of dataclasses and classes that use dataclass_transform (Jacek Chałupka, PR14854)
Allow iterable class objects to be unpacked (including enums) (Alex Waygood, PR14827)
Fix narrowing for walrus expressions used in match statements (Shantanu, PR14844)
Add signature for attr.evolve (Ilya Konstantinov, PR14526)
Fix Any inference when unpacking iterators that don’t directly inherit from typing.Iterator (Alex Waygood, PR14821)
Fix unpack with overloaded__iter__ method (Nikita Sobolev, PR14817)
Reduce size of JSON data in mypy cache (dosisod, PR14808)
Improve “used before definition” checks when a local definition has the same name as a global definition (Stas Ilinskiy, PR14517)
Honor NoReturn as __setitem__ return type to mark unreachable code (sterliakov, PR12572)
Typeshed is now modular and distributed as separate PyPI packages for everything except the standard library stubs. Please seegit log for full list of typeshed changes.
Thanks to all mypy contributors who contributed to this release:
Alex Waygood
Avasam
Christoph Tyralla
dosisod
EXPLOSION
Ilya Konstantinov
Ivan Levkivskyi
Jacek Chałupka
Jelle Zijlstra
Jukka Lehtosalo
Marc Mueller
Max Murin
Nikita Sobolev
Richard Si
Shantanu
Stas Ilinskiy
sterliakov
Wesley Collin Wright
Posted by Jukka Lehtosalo
We’ve just uploaded mypy 1.1.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 onRead the Docs.
This release adds full support for the dataclass_transform decorator defined inPEP 681. This allows decorators, base classes, and metaclasses that generate a __init__ method or other methods based on the properties of that class (similar to dataclasses) to have those methods recognized by mypy.
This was contributed by Wesley Collin Wright.
Mypy can’t safely check all assignments to methods (a form of monkey patching), so mypy generates an error by default. To make it easier to ignore this error, mypy now uses the new error code method-assign for this. By disabling this error code in a file or globally, mypy will no longer complain about assignments to methods if the signatures are compatible.
Mypy also supports the old error code assignment for these assignments to prevent a backward compatibility break. More generally, we can use this mechanism in the future if we wish to split or rename another existing error code without causing backward compatibility issues.
This was contributed by Ivan Levkivskyi (PR14570).
Fix generic TypedDict/NamedTuple caching (Ivan Levkivskyi, PR14675)
Raise “non-trait base must be first…” error less frequently (Richard Si, PR14468)
Generate faster code for bool comparisons and arithmetic (Jukka Lehtosalo, PR14489)
Optimize __(a)enter__/__(a)exit__ for native classes (Jared Hance, PR14530)
Detect if attribute definition conflicts with base class/trait (Jukka Lehtosalo, PR14535)
Support __(r)divmod__ dunders (Richard Si, PR14613)
Support __pow__, __rpow__, and __ipow__ dunders (Richard Si, PR14616)
Fix crash on star unpacking to underscore (Ivan Levkivskyi, PR14624)
Fix iterating over a union of dicts (Richard Si, PR14713)
Stubgen is a tool for automatically generating draft stubs for libraries.
Stubtest is a tool for testing that stubs conform to the implementations.
Add new TypedDict error code typeddict-unknown-key (JoaquimEsteves, PR14225)
Give arguments a more reasonable location in error messages (Max Murin, PR14562)
In error messages, quote just the module’s name (Ilya Konstantinov, PR14567)
Improve misleading message about Enum() (Rodrigo Silva, PR14590)
Suggest importing fromtyping_extensions if definition is not in typing (Shantanu, PR14591)
Consistently use type-abstract error code (Ivan Levkivskyi, PR14619)
Consistently use literal-required error code for TypedDicts (Ivan Levkivskyi, PR14621)
Adjust inconsistent dataclasses plugin error messages (Wesley Collin Wright, PR14637)
Consolidate literal bool argument error messages (Wesley Collin Wright, PR14693)
Check that type guards accept a positional argument (EXPLOSION, PR14238)
Fix bug with in operator used with a union of Container and Iterable (Max Murin, PR14384)
Support protocol inference for type[T] via metaclass (Ivan Levkivskyi, PR14554)
Allow overlapping comparisons between bytes-like types (Shantanu, PR14658)
Fix mypy daemon documentation link in README (Ivan Levkivskyi, PR14644)
Typeshed is now modular and distributed as separate PyPI packages for everything except the standard library stubs. Please seegit log for full list of typeshed changes.
Thanks to all mypy contributors who contributed to this release:
Alex Waygood
Avasam
Chad Dombrova
dosisod
EXPLOSION
hamdanal
Ilya Konstantinov
Ivan Levkivskyi
Jared Hance
JoaquimEsteves
Jukka Lehtosalo
Marc Mueller
Max Murin
Michael Lee
Michael R. Crusoe
Richard Si
Rodrigo Silva
Shantanu
Stas Ilinskiy
Wesley Collin Wright
Yilei “Dolee” Yang
Yurii Karabas
We’d also like to thank our employer, Dropbox, for funding the mypy core team.
Posted by Max Murin
We’ve just uploaded mypy 1.0 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 onRead the Docs.
Now that mypy reached 1.0, we’ll switch to a new versioning scheme. Mypy version numbers will be of form x.y.z.
Rules:
The major release number (x) is incremented if a feature release includes a significant backward incompatible change that affects a significant fraction of users.
The minor release number (y) is incremented on each feature release. Minor releases include updated stdlib stubs from typeshed.
The point release number (z) is incremented when there are fixes only.
Mypy doesn’t use SemVer, since most minor releases have at least minor backward incompatible changes in typeshed, at the very least. Also, many type checking features find new legitimate issues in code. These are not considered backward incompatible changes, unless the number of new errors is very high.
Any significant backward incompatible change must be announced in the blog post for the previous feature release, before making the change. The previous release must also provide a flag to explicitly enable or disable the new behavior (whenever practical), so that users will be able to prepare for the changes and report issues. We should keep the feature flag for at least a few releases after we’ve switched the default.
See”Release Process” in the mypy wiki for more details and for the most up-to-date version of the versioning scheme.
Mypy 1.0 is up to 40% faster than mypy 0.991 when type checking the Dropbox internal codebase. We also set up a daily job to measure the performance of the most recent development version of mypy to make it easier to track changes in performance.
Many optimizations contributed to this improvement:
Improve performance for errors on class with many attributes (Shantanu, PR14379)
Speed up make_simplified_union (Jukka Lehtosalo, PR14370)
Micro-optimize get_proper_type(s) (Jukka Lehtosalo, PR14369)
Micro-optimize flatten_nested_unions (Jukka Lehtosalo, PR14368)
Some semantic analyzer micro-optimizations (Jukka Lehtosalo, PR14367)
A few miscellaneous micro-optimizations (Jukka Lehtosalo, PR14366)
Optimization: Avoid a few uses of contextmanagers in semantic analyzer (Jukka Lehtosalo, PR14360)
Optimization: Enable always defined attributes in Type subclasses (Jukka Lehtosalo, PR14356)
Optimization: Remove expensive context manager in type analyzer (Jukka Lehtosalo, PR14357)
subtypes: fast path for Union/Union subtype check (Hugues, PR14277)
Micro-optimization: avoid Bogus[int] types that cause needless boxing (Jukka Lehtosalo, PR14354)
Avoid slow error message logic if errors not shown to user (Jukka Lehtosalo, PR14336)
Speed up the implementation of hasattr() checks (Jukka Lehtosalo, PR14333)
Avoid the use of a context manager in hot code path (Jukka Lehtosalo, PR14331)
Change various type queries into faster bool type queries (Jukka Lehtosalo, PR14330)
Speed up recursive type check (Jukka Lehtosalo, PR14326)
Optimize subtype checking by avoiding a nested function (Jukka Lehtosalo, PR14325)
Optimize type parameter checks in subtype checking (Jukka Lehtosalo, PR14324)
Speed up freshening type variables (Jukka Lehtosalo, PR14323)
Optimize implementation of TypedDict types for **kwds (Jukka Lehtosalo, PR14316)
Mypy will now generate an error if you use a variable before it’s defined. This feature is enabled by default. By default mypy reports an error when it infers that a variable is always undefined.
y=x# E: Name "x" is used before definition [used-before-def]x=0
This feature was contributed by Stas Ilinskiy.
A new experimental possibly-undefined error code is now available that will detect variables that may be undefined:
ifb:x=0print(x)# Error: Name "x" may be undefined [possibly-undefined]
The error code is disabled be default, since it can generate false positives.
This feature was contributed by Stas Ilinskiy.
There is now a simpler syntax for declaringgeneric self types introduced inPEP 673: the Self type. You no longer have to define a type variable to use “self types”, and you can use them with attributes. Example from mypy documentation:
fromtypingimportSelfclassFriend:other:Self|None=None@classmethoddefmake_pair(cls)->tuple[Self,Self]:a,b=cls(),cls()a.other=bb.other=areturna,bclassSuperFriend(Friend):pass# a and b have the inferred type "SuperFriend", not "Friend"a,b=SuperFriend.make_pair()
The feature was introduced in Python 3.11. In earlier Python versions a backport of Self is available intyping_extensions.
This was contributed by Ivan Levkivskyi (PR14041).
ParamSpec and Concatenate can now be used in type aliases. Example:
fromtypingimportParamSpec,CallableP=ParamSpec("P")A=Callable[P,None]deff(c:A[int,str])->None:c(1,"x")
This feature was contributed by Ivan Levkivskyi (PR14159).
Support for ParamSpec (PEP 612) and generic self types are no longer considered experimental.
Minimal, partial implementation of dataclass_transform (PEP 681) (Wesley Collin Wright, PR14523)
Add basic support fortyping_extensions.TypeVar (Marc Mueller, PR14313)
Add –debug-serialize option (Marc Mueller, PR14155)
Constant fold initializers of final variables (Jukka Lehtosalo, PR14283)
Enable Final instance attributes for attrs (Tin Tvrtković, PR14232)
Allow function arguments as base classes (Ivan Levkivskyi, PR14135)
Allow super() with mixin protocols (Ivan Levkivskyi, PR14082)
Add type inference for dict.keys membership (Matthew Hughes, PR13372)
Generate error for class attribute access if attribute is defined with__slots__ (Harrison McCarty, PR14125)
Support additional attributes in callback protocols (Ivan Levkivskyi, PR14084)
Fix crash on prefixed ParamSpec with forward reference (Ivan Levkivskyi, PR14569)
Fix internal crash when resolving the same partial type twice (Shantanu, PR14552)
Fix crash in daemon mode on new import cycle (Ivan Levkivskyi, PR14508)
Fix crash in mypy daemon (Ivan Levkivskyi, PR14497)
Fix crash on Any metaclass in incremental mode (Ivan Levkivskyi, PR14495)
Fix crash in await inside comprehension outside function (Ivan Levkivskyi, PR14486)
Fix crash in Self type on forward reference in upper bound (Ivan Levkivskyi, PR14206)
Fix a crash when incorrect super() is used outside a method (Ivan Levkivskyi, PR14208)
Fix crash on overriding with frozen attrs (Ivan Levkivskyi, PR14186)
Fix incremental mode crash on generic function appearing in nested position (Ivan Levkivskyi, PR14148)
Fix daemon crash on malformed NamedTuple (Ivan Levkivskyi, PR14119)
Fix crash during ParamSpec inference (Ivan Levkivskyi, PR14118)
Fix crash on nested generic callable (Ivan Levkivskyi, PR14093)
Fix crashes with unpacking SyntaxError (Shantanu, PR11499)
Fix crash on partial type inference within a lambda (Ivan Levkivskyi, PR14087)
Fix crash with enums (Michael Lee, PR14021)
Fix crash with malformed TypedDicts and disllow-any-expr (Michael Lee, PR13963)
Mypyc can now compile Python 3.10 match statements.
This was contributed by dosisod (PR13953).
Optimize int(x)/float(x)/complex(x) on instances of native classes (Richard Si, PR14450)
Always emit warnings (Richard Si, PR14451)
Faster bool and integer conversions (Jukka Lehtosalo, PR14422)
Support attributes that override properties (Jukka Lehtosalo, PR14377)
Precompute set literals for “in” operations and iteration (Richard Si, PR14409)
Don’t load targets with forward references while setting up non-extension class__all__ (Richard Si, PR14401)
Compile away NewType type calls (Richard Si, PR14398)
Improve error message for multiple inheritance (Joshua Bronson, PR14344)
Simplify union types (Jukka Lehtosalo, PR14363)
Fixes to union simplification (Jukka Lehtosalo, PR14364)
Fix for typeshed changes to Collection (Shantanu, PR13994)
Allow use of enum.Enum (Shantanu, PR13995)
Fix compiling on Arch Linux (dosisod, PR13978)
Various documentation and error message tweaks (Jukka Lehtosalo, PR14574)
Improve Generics documentation (Shantanu, PR14587)
Improve protocols documentation (Shantanu, PR14577)
Improve dynamic typing documentation (Shantanu, PR14576)
Improve the Common Issues page (Shantanu, PR14581)
Add a top-level TypedDict page (Shantanu, PR14584)
More improvements to getting started documentation (Shantanu, PR14572)
Move truthy-function documentation from “optional checks” to “enabled by default” (Anders Kaseorg, PR14380)
Avoid use of implicit optional in decorator factory documentation (Tom Schraitle, PR14156)
Clarify documentation surrounding install-types (Shantanu, PR14003)
Improve searchability for module level type ignore errors (Shantanu, PR14342)
Advertise mypy daemon in README (Ivan Levkivskyi, PR14248)
Add link to error codes in README (Ivan Levkivskyi, PR14249)
Document that report generation disables cache (Ilya Konstantinov, PR14402)
Stop saying mypy is beta software (Ivan Levkivskyi, PR14251)
Flycheck-mypy is deprecated, since its functionality was merged to Flycheck (Ivan Levkivskyi, PR14247)
Update code example in “Declaring decorators” (ChristianWitzler, PR14131)
Stubtest is a tool for testing that stubs conform to the implementations.
Improve error message for__all__-related errors (Alex Waygood, PR14362)
Improve heuristics for determining whether global-namespace names are imported (Alex Waygood, PR14270)
Catch BaseException on module imports (Shantanu, PR14284)
Associate exported symbol error with__all__ object_path (Nikita Sobolev, PR14217)
Add __warningregistry__ to the list of ignored module dunders (Nikita Sobolev, PR14218)
If a default is present in the stub, check that it is correct (Jelle Zijlstra, PR14085)
Stubgen is a tool for automatically generating draft stubs for libraries.
Treat dlls as C modules (Shantanu, PR14503)
Update stub suggestions based on recent typeshed changes (Alex Waygood, PR14265)
Fix attrs protocol check with cache (Marc Mueller, PR14558)
Fix strict equality check if operand item type has custom __eq__ (Jukka Lehtosalo, PR14513)
Don’t consider object always truthy (Jukka Lehtosalo, PR14510)
Properly support union of TypedDicts as dict literal context (Ivan Levkivskyi, PR14505)
Properly expand type in generic class with Self and TypeVar with values (Ivan Levkivskyi, PR14491)
Fix recursive TypedDicts/NamedTuples defined with call syntax (Ivan Levkivskyi, PR14488)
Fix type inference issue when a class inherits from Any (Shantanu, PR14404)
Fix false positive on generic base class with six (Ivan Levkivskyi, PR14478)
Don’t read scripts without extensions as modules in namespace mode (Tim Geypens, PR14335)
Fix inference for constrained type variables within unions (Christoph Tyralla, PR14396)
Fix Unpack imported from typing (Marc Mueller, PR14378)
Allow trailing commas in ini configuration of multiline values (Nikita Sobolev, PR14240)
Fix false negatives involving Unions and generators or coroutines (Shantanu, PR14224)
Fix ParamSpec constraint for types as callable (Vincent Vanlaer, PR14153)
Fix type aliases with fixed-length tuples (Jukka Lehtosalo, PR14184)
Fix issues with type aliases and new style unions (Jukka Lehtosalo, PR14181)
Simplify unions less aggressively (Ivan Levkivskyi, PR14178)
Simplify callable overlap logic (Ivan Levkivskyi, PR14174)
Try empty context when assigning to union typed variables (Ivan Levkivskyi, PR14151)
Improvements to recursive types (Ivan Levkivskyi, PR14147)
Make non-numeric non-empty FORCE_COLOR truthy (Shantanu, PR14140)
Fix to recursive type aliases (Ivan Levkivskyi, PR14136)
Correctly handle Enum name on Python 3.11 (Ivan Levkivskyi, PR14133)
Fix class objects falling back to metaclass for callback protocol (Ivan Levkivskyi, PR14121)
Correctly support self types in callable ClassVar (Ivan Levkivskyi, PR14115)
Fix type variable clash in nested positions and in attributes (Ivan Levkivskyi, PR14095)
Allow class variable as implementation for read only attribute (Ivan Levkivskyi, PR14081)
Prevent warnings from causing dmypy to fail (Andrzej Bartosiński, PR14102)
Correctly process nested definitions in mypy daemon (Ivan Levkivskyi, PR14104)
Don’t consider a branch unreachable if there is a possible promotion (Ivan Levkivskyi, PR14077)
Fix incompatible overrides of overloaded methods in concrete subclasses (Shantanu, PR14017)
Fix new style union syntax in type aliases (Jukka Lehtosalo, PR14008)
Fix and optimise overload compatibility checking (Shantanu, PR14018)
Improve handling of redefinitions through imports (Shantanu, PR13969)
Preserve (some) implicitly exported types (Shantanu, PR13967)
Typeshed is now modular and distributed as separate PyPI packages for everything except the standard library stubs. Please seegit log for full list of typeshed changes.
Thanks to all mypy contributors who contributed to this release:
Alessio Izzo
Alex Waygood
Anders Kaseorg
Andrzej Bartosiński
Avasam
ChristianWitzler
Christoph Tyralla
dosisod
Harrison McCarty
Hugo van Kemenade
Hugues
Ilya Konstantinov
Ivan Levkivskyi
Jelle Zijlstra
jhance
johnthagen
Jonathan Daniel
Joshua Bronson
Jukka Lehtosalo
KotlinIsland
Lakshay Bisht
Lefteris Karapetsas
Marc Mueller
Matthew Hughes
Michael Lee
Nick Drozd
Nikita Sobolev
Richard Si
Shantanu
Stas Ilinskiy
Tim Geypens
Tin Tvrtković
Tom Schraitle
Valentin Stanciu
Vincent Vanlaer
We’d also like to thank our employer, Dropbox, for funding the mypy core team.
Posted by Stas Ilinskiy
For information about previous releases, refer to the posts at https://mypy-lang.blogspot.com/
__getattr__,__setattr__, and__delattr____new__--force-uppercase-builtins--strict-bytesfunctools.partial**kwargs Typing