Friday, 22 January 2021

Mypy 0.800 Released

We’ve just uploaded mypy 0.800 to the Python Package Index (PyPI). Mypy is a static type checker for Python. This release includes new features, bug fixes and library stub (typeshed) updates. You can install it as follows:

    python3 -m pip install -U mypy

You can read the full documentation for this release on Read the Docs.

Python 3.9 Support

Mypy 0.800 officially supports the recently released Python 3.9. We now provide compiled binary wheels for Python 3.9, improving type checking speed significantly.

Typing Usability Improvements (PEP 585 and PEP 604)

The necessity to repeatedly import various types and special forms from typing has been a long-term nuisance for users of static type checking and Python.

Two new Python features improve this situation and are now supported by mypy:

  • PEP 585 lets you use list[int] instead of List[int] (no need to import List and other generic collections from typing).
  • PEP 604 lets you write X | Y instead of Union[X, Y], and X | None instead of Optional[X] (no need to import Union or Optional from typing).

Note: Using list[int] requires Python 3.9 and X | Y requires Python 3.10 (alpha) in order to work at runtime. To use them on older versions of Python, use from __future__ import annotations. This allows them to be used in type annotations, but the older variants (or string literal escaping) may be required in non-annotation contexts, such as in type aliases. See the docs for more details.

Here is an example that uses the new features:

    from __future__ import annotations
    
    def fields(s: str | None) -> list[str]:
        if not s:
            return []
        else:
            return s.split(',')

These were implemented by Allan Daemon in PR 9564 and by Marc Mueller in PR 9647.

Improvements to Finding Modules

This release adds several improvements to how mypy finds Python source files to type check.

You can now pass paths to files within namespace packages on the command line, and mypy can better infer their module names. As before, use --namespace-packages to enable namespace packages.

When you use --explicit-package-bases together with --namespace-packages, mypy assumes that only the current directory and directories explicitly specified in MYPYPATH (or mypy_path in the config file) are valid package roots. This can help with situations where the module name of a file is ambiguous. For example, it may not be clear whether src/pkg/mod.py should be treated as src.pkg.mod or pkg.mod, and you can use this option to disambiguate between the two (more information in the docs).

The above improvements were implemented in PR 9742 by Shantanu.

Other related improvements (also implemented by Shantanu):

  • When you run mypy as mypy <directory>, look for source files recursively also inside directories without a __init__.py (PR 9614)
  • Support namespace packages with -p (PR 9683)
  • Log encountered source files when running mypy with -v (PR 9672)
  • Document the new module finding behavior (PR 9923)

Other Notable Improvements and Bug Fixes

  • Only treat import X as X as a re-export in stubs (Shantanu, PR 9515)
  • Fix package imports with aliases in stubgen (Chad Dombrova, PR 9534)
  • Require first argument of namedtuple() to match the variable name (Momoko Hattori, PR 9577)
  • Add error code for name mismatches in named tuples and TypedDicts to make it easy to disable these error messages (Jukka Lehtosalo, PR 9811)
  • Document local_partial_types config option (Momoko Hattori, PR 9551)
  • Improve ambiguous kwargs checking (Erik Soma, PR 9573)
  • Disable unreachable warnings in boolean operators for type variables with value restrictions (Vincent Barbaresi, PR 9572)
  • Allow assignment to an empty tuple (Tobin Yehle, PR 5617)
  • Use absolute path when checking source duplication error (Yuki Igarashi, PR 9059)
  • Add get_function_signature_hook() to the plugin API (Nikita Sobolev, PR 9102)
  • Speed up type checking of dictionary, set, and list expressions (Hugues, PR 9477)
  • Allow non-types as arguments in Annotated (Patrick Arminio, PR 9625)
  • Add support for next generation attrs API (David Euresti, PR 9396)
  • Fix case folding of missing keys error message for TypedDicts (Marti Raudsepp, PR 9757)
  • Fix generic inheritance of __init__() methods in dataclasses and attrs classes (Nate McMaster, PR 9383, PR 9380)
  • Add more information to error message on too few arguments (Abhinay Pandey, PR 9796)
  • Document PEP 585, 563, 604, and related functionality (Shantanu, PR 9763)

Mypyc Improvements

We use mypyc to compile mypy into fast C extension modules. This release includes many mypyc improvements.

Xuanda Yang finished the migration to use a new, lower-level compiler intermediate representation in his Google Summer of Code project.

New supported Python features:

  • Support the walrus operator (:=) (Michael J. Sullivan, PR 9624)

Performance improvements:

  • Add primitives for list sort and list reverse (Jukka Lehtosalo, PR 9897)
  • Recognize six.moves.xrange again as an alias of range (Jukka Lehtosalo, PR 9896)
  • Speed up some integer primitives (Jukka Lehtosalo, PR 9801)
  • Speed up if x for int values (Jukka Lehtosalo, PR 9854)
  • Implement dict clear primitive (Vasileios Sakkas, PR 9724)
  • Implement list insert primitive (Vasileios Sakkas, PR 9741)
  • Implement float abs primitive (Xuanda Yang, PR 9695)
  • Implement str-to-float primitive (Xuanda Yang, PR 9685)
  • Specialize some calls to frozenset (Michael J. Sullivan, PR 9623)
  • Speed up multiple assignment from tuple (Xuanda Yang, PR 9575)
  • Speed up multiple assignment from sequence (Jukka Lehtosalo, PR 9800)
  • Optimize startswith and endswith (Tomer Chachamu, PR 9557)
  • Add primitives for bitwise ops (Jukka Lehtosalo, PR 9529)
  • Speed up in operations for list/tuple (Johan Dahlin, PR 9004)
  • Add primitives for list, str and tuple slicing (Jukka Lehtosalo, PR 9283)
  • Speed up tuple equality checks (Xuanda Yang, PR 9343)

Bug fixes:

  • Always add implicit None return type to __init__ method (Thomas Johnson, PR 9866)
  • Fix deallocation of deeply nested data structures (Michael J. Sullivan, PR 9839)
  • Fix using package imported inside a function (Jukka Lehtosalo, PR 9782)
  • Fix type of for loop index register in for over range (Jukka Lehtosalo, PR 9634)

Typeshed Updates

Many improvements were made to typeshed — too many to list. Browse the typeshed commit log here.

Acknowledgments

First of all, we’d like to thank our employer, Dropbox, for funding the mypy core team.

Thanks to all mypy contributors who contributed to this release:

  • Abdullah Selek
  • Abhinay Pandey
  • Adam
  • aghast
  • Akuli
  • Alexander
  • Allan Daemon
  • Aristotelis Mikropoulos
  • Ashley Whetter
  • Brian Mboya
  • Bryan Forbes
  • cdce8p
  • Chad Dombrova
  • David Euresti
  • Denis Laxalde
  • Eisuke Kawashima
  • Erik Soma
  • Ethan Pronovost
  • Florian Bruhin
  • Frank Dana
  • Greg Compestine
  • Guido van Rossum
  • Hugues
  • Jake Bailey
  • Jakub Stasiak
  • Jelle Zijlstra
  • Jeremy Metz
  • Johan Dahlin
  • Jon Shea
  • Jonathan Wong
  • Jürgen Gmach
  • Kamil Turek
  • Krzysztof Przybyła
  • Lawrence Chan
  • Marti Raudsepp
  • Matan Gover
  • Matt Gilson
  • Michael J. Sullivan
  • Momoko Hattori
  • Nate McMaster
  • Nikita Sobolev
  • Nils K
  • Nipunn Koorapati
  • Oleg Höfling
  • Patrick Arminio
  • Rajiv Singh
  • rhkleijn
  • Roland van Laar
  • Shantanu
  • Tobin Yehle
  • Tom Scogland
  • Tomer Chachamu
  • Tripp Horbinski
  • Ville Skyttä
  • Vincent Barbaresi
  • vsakkas
  • Wes Turner
  • willtryagain
  • Xiaodong DENG
  • Xuanda Yang
  • Yash Chhabria
  • Yuki Igarashi

Additional thanks to all contributors to typeshed:

  • Abraham Francis
  • Adam Dangoor
  • Adam Kliś
  • Adam Lichtl
  • Akuli
  • alexander-held
  • an onion
  • Anders Kaseorg
  • Andrew Mitchell
  • Árni Már Jónsson
  • Ash Berlin-Taylor
  • Ashwin Vishnu
  • Avery
  • cdce8p
  • Cebtenzzre
  • Changsheng
  • Christine
  • coiax
  • cptpcrd
  • crusaderky
  • Daniel O'Neel
  • David Caro
  • Dominic Davis-Foster
  • Eric Traut
  • Ethan Pronovost
  • Frank Maximilian
  • Gal Ben David
  • github-actions[bot]
  • Guido van Rossum
  • henribru
  • Hong Xu
  • Hugues
  • Hynek Schlawack
  • jack1142
  • Jake Bailey
  • Jason Fried
  • Jelle Zijlstra
  • Jia Chen
  • Jon Dufresne
  • Jonathan Schoonhoven
  • Jonathan Slenders
  • Joseph Haaga
  • Julien Danjou
  • Jun Jia
  • Jérome Perrin
  • karl ding
  • Katelyn Gigante
  • Kaushal Rohit
  • Kevin Wojniak
  • ky-gog
  • Kyle Fuller
  • kylec1
  • Lam Son Ho
  • Lourens Veen
  • Mahmoud Abduljawad
  • Mariam Maarouf
  • Marti Raudsepp
  • melassa
  • Mickaël Schoentgen
  • Mikhail Sveshnikov
  • Mikołaj Kuranowski
  • Moriyoshi Koizumi
  • Nate McMaster
  • Neel Somani
  • nicolas-harraudeau-sonarsource
  • Nikolaus Waxweiler
  • Nils K
  • Nipunn Koorapati
  • Oleg Höfling
  • Omar Sandoval
  • Paul
  • Pete Scopes
  • Peter Law
  • Philipp Hahn
  • Phillip Huang
  • proost
  • PythonCoderAS
  • Rajiv Bakulesh Shah
  • Ran Benita
  • Raphael Geronimi
  • Rebecca Chen
  • Sam Bull
  • Sebastian Rittau
  • Sergei Lebedev
  • Shantanu
  • Stefano Chiodino
  • Steve Dignam
  • Sténio Jacinto
  • Timur Kushukov
  • Tom Most
  • turettn
  • Unrud
  • Utsav
  • Vasily Zakharov
  • Vincent Barbaresi
  • Vincent Meurisse
  • 愚氓
  • Yuri Khan

Friday, 9 October 2020

Mypy 0.790 Released

We’ve just uploaded mypy 0.790 to the Python Package Index (PyPI). Mypy is a static type checker for Python. This release includes new features, bug fixes and library stub (typeshed) updates. You can install it as follows:

    python3 -m pip install -U mypy

You can read the full documentation for this release on Read the Docs.

Note that mypy 0.790 doesn’t yet officially support the recently released Python 3.9.

Enabling and Disabling Error Codes

You can now globally disable and enable the generation of error messages with specific error codes by using --enable-error-code and --disable-error-code command line options (and config file options). This lets you disallow certain checks that don’t provide value or are too noisy, and in the future these can be used to enable optional, stricter checks. For more information, read the documentation.

This was contributed by Callum Wilkinson (PR 9172).

Bug Fixes

  • Fix disable_error_code config file option (Aristotelis Mikropoulos, PR 9538)
  • Fix partial type crash during protocol checking (Shantanu, PR 9495)
  • Store the type for assignment expression (walrus) targets (Lawrence Chan, PR 9479)
  • Always type check arguments when using --disallow-untyped-calls (PR 9510)
  • Make None compatible with Hashable (PR 9371)
  • Don't infinite loop on self dependencies in --follow-imports=normal (Michael J. Sullivan, PR 9302)
  • Don't simplify away Any when joining union types (PR 9301)
  • Check for deleted vars in raise from (Alexandre Viau, PR 9272)
  • Fix corner case for comparing nested overloads (Nikita Sobolev, PR 9259)
  • Fix issues with async for and with statements (Guido van Rossum, PR 9268)
  • Fix internal error on list/dict comprehension with walrus operator in global scope (dhood, PR 9062)
  • Fix propagation of module-specific options to the parser (Guido van Rossum, PR 9247)
  • Fix crash when super is called outside a method (Weiss, PR 9173)
  • Fix untyped decorator overload error on class decorator with __call__ overloads (Ran Benita, PR 9232)
  • Clean up terminal width handling (Florian Bruhin, PR 9143)
  • Add keyword arguments for functional Enum API (LiuYuhui, PR 9123)
  • Validate follow_imports values in mypy.ini (Michael J. Sullivan, PR 9165)
  • Fix *expr in an assigned expression (LiuYuhui, PR 8827)
  • Don't consider comparing True and False as a dangerous comparison (PR 9021)
  • Make reveal_type work with call expressions returning None (Jakub Stasiak, PR 8924)

Error Reporting Improvements

  • Improve missing module error for subdirectories (Ethan Leba, PR 8927)
  • Clarify bytes formatting error messages (Shantanu, PR 9243)
  • Fix misleading follow_imports error message in dmypy (Michael J. Sullivan, PR 9167)
  • Use [arg-type] error code for additional argument type error messages (PR 9090)
  • Report some additional serious errors in junit.xml (PR 8950)
  • Report note about binary operation on the same location as error message (PR 8936)

Documentation Updates

  • Document disable_error_code config file option (Aristotelis Mikropoulos, PR 9539)
  • Add cross references to config file values (Oleg Höfling, PR 7859)
  • Add cross references to additional config values, and missing plugins config value, and document --help option for stubgen (Oleg Höfling, PR 9241)
  • Remove note that Final is experimental and suggest importing it from typing (Ran Benita, PR 9138)
  • Discuss unreachable code as a common issue (Chetan Khanna, PR 8899)

Stubgen Improvements

  • Improve property type detection in extension modules (Antoine Prouvost, PR 8999)
  • Fix type stubgen crash caused by invalid type annotation (Henry Schreiner, PR 8888)
  • Import Iterable and Iterator from typing in generated stubs (Ashley Whetter, PR 9088)

Other Improvements

  • Speed up type checking of unions containing many literal string types (Akuli, PR 9192)
  • Add scripts to misc/ (in the mypy GitHub repository) for computing and applying diffs of mypy caches to enable incremental cache downloads (Michael J. Sullivan, PR 8906)

Internal Changes

This release includes several improvements to mypyc, the compiler we use to speed up mypy. Most notably, Xuanda Yang has been migrating mypyc to use a new, lower-level intermediate representation in his Google Summer of Code project. This provides a solid foundation for a variety of future mypyc improvements.

Additional mypyc improvements:

  • Dynamically disallow instantiating traits/interpreted subclasses (Michael J. Sullivan, PR 9248)
  • Basic support for protocols (Michael J. Sullivan, PR 8914)
  • Various optimizations (PR 8903, PR 8870; Michael J. Sullivan and Xuanda Yang, PR 9245)
  • Make it easier to write mypyc test cases (PR 9094)

Typeshed Updates

Many improvements were made to typeshed — too many to list. Browse the typeshed commit log here.

Acknowledgments

First of all, we’d like to thank our employer, Dropbox, for funding the mypy core team.

Thanks to all mypy contributors who contributed to this release:

  • Akuli
  • Alexandre Viau
  • Antoine Lecubin
  • Antoine Prouvost
  • Aristotelis Mikropoulos
  • Ashley Whetter
  • Ben Wolsieffer
  • Brian Mboya
  • Callum Wilkinson
  • Chetan Khanna
  • dhood
  • Ethan Leba
  • Florian Bruhin
  • Henry Schreiner
  • ishaan
  • Jakub Stasiak
  • Jelle Zijlstra
  • Lawrence Chan
  • LiuYuhui
  • Michael R. Crusoe
  • Michael Sullivan
  • Nikita Sobolev
  • Oleg Höfling
  • Ram Rachum
  • Ran Benita
  • Rune Tynan
  • Shantanu
  • Weiss
  • Xuanda Yang
  • 谭九鼎

Additional thanks to all contributors to typeshed:

  • Adam Hitchcock
  • Akuli
  • Alex Grönholm
  • Anders Kaseorg
  • Andre Delfino
  • Andreas Poehlmann
  • Artem Simonov
  • Batuhan Taskaya
  • Brad Solomon
  • Brian Wellington
  • Bruce Merry
  • Cerek Hillen
  • Christine
  • Christopher Head
  • Christopher Schramm
  • Dakkaron
  • Dan Palmer
  • David Hotham
  • Denis Laxalde
  • Dmitry Marakasov
  • Eric Masseran
  • Eric N. Vander Weele
  • Eric Traut
  • Federico Bond
  • frehoy
  • Gregory P. Smith
  • helafumpek
  • Ian Good
  • Ian Woloschin
  • Igor Nehoroshev
  • Ilaï Deutel
  • Ilya Konstantinov
  • Jakub Stasiak
  • James Weaver
  • Jaromir Latal
  • Jelle Zijlstra
  • Jia Chen
  • John Snow
  • Jonathan Slenders
  • Joshua Oreman
  • Julian Mehnle
  • Julin S
  • Jürgen Gmach
  • Karl Ding
  • Kevin Wojniak
  • Kunal Arya
  • Luciano Ramalho
  • Magnus Watn
  • MapleCCC
  • Mario Ishac
  • Mark Mendoza
  • Markus Pielmeier
  • Martijn Pieters
  • Matan Gover
  • Michael H
  • Mikhail Golubev
  • Milap Sheth
  • Nils K
  • Nipunn Koorapati
  • Omar Sandoval
  • Peter Law
  • Philipp Hahn
  • Phillip Huang
  • Ran Benita
  • Rebecca Chen
  • Rich Li
  • Rune Tynan
  • Russell Davis
  • Sabby6
  • Sam Bull
  • Sebastian Kreft
  • Sebastian Rittau
  • Selim Belhaouane
  • Shannon Zhu
  • Shantanu
  • Steve B
  • Steve Dignam
  • Tarcisio
  • Teddy Sudol
  • Toru Ogawa
  • Vegard Stikbakke
  • Vishal Kuo
  • Vlad Emelianov
  • Willy Wu
  • Wouter Bolsterlee
  • Áron Ricardo Perez-Lopez

Wednesday, 3 June 2020

Mypy 0.780 Released

Mypy 0.780 Released

We’ve just uploaded mypy 0.780 to the Python Package Index (PyPI). Mypy is a static type checker for Python. This release includes new features, bug fixes and library stub (typeshed) updates. You can install it as follows:

    python3 -m pip install -U mypy

You can read the full documentation for this release on Read the Docs.

Following Imports in Mypy Daemon

You can now leave out the --follow-imports option when running dmypy, and mypy daemon will follow imports, similar to a non-daemon mypy run:

    dmypy run -- prog.py pkg/*.py

Previously mypy daemon did not support this, and it was necessary to use --follow-imports and explicitly mention all files to check on the command line. (Following imports in mypy daemon is an experimental feature.)

See the docs about following import in mypy.

Miscellaneous New Features

  • Support environment variable interpolation for junit_xml configuration key (Mattwmaster58, PR 8479)
  • Add no_site_packages config file setting (davidzwa, PR 8524)
  • Allow .mypy.ini (with a dot prefix) as an alternative name to mypy.ini (dosisod, PR 8515)
  • Disallow unpacking of strings in multiple assignment, as this is usually a bug (Abtin, PR 8589)
  • Allow type aliases in a runtime (non-type) context (PR 8779)
  • Add narrowing unions with bool literals via identity check (Steve Dignam, PR 8821)
  • Always allow to cast to Any without warnings (oda, PR 8544)
  • Suggest solutions for a typo in a key of a TypedDict (Felicián Németh, PR 8483)
  • Provide more context about why incompatible with supertype is an error (Chetan Khanna, PR 8866)

Other Notable Improvements and Bug Fixes

  • Fix handling dependencies to __call__ in mypy daemon (PR 8494)
  • Various improvements to stubtest (PR 8502, PR 8886) (Shantanu)
  • Fix invalid type causing named tuple errors reported in wrong files (PR 8549)
  • Clarify documentation of Liskov substitution principle (PR 8563)
  • Fix type inference with lambda that returns None (PR 8562)
  • Fix incremental crash bug caused by NewType in functions (PR 8607)
  • Fix indexed assignment check when TypedDict is used as upper bound (Xuanda Yang, PR 8621)
  • Improve error message for bad indexed assignment (pando, PR 8641)
  • Fix crash when the same file is processed under multiple names (PR 8644)
  • Fix parser when using Python 3.9 (PR 8716)
  • Accept dict() as an empty dictionary in a TypedDict context (PR 8749)
  • Fix incorrect coroutine return type for nested function (Jens Widell, PR 8741)
  • Reject bytes literal as a TypedDict key (PR 8782)
  • Allow attrs keyword-only arguments at any position (Markus Schmaus, PR 8803)
  • Detect duplicate keys in call-based TypedDict definitions (PR 8849)
  • Look at arguments when generating constraints for an overload (PR 8845)
  • Fix potential wrong-file error message for unsupported types (PR 8854)

Typeshed Updates

Many small improvements were made to typeshed — too many to list. Browse the typeshed commit log here.

Acknowledgments

First of all, we’d like to thank our employer, Dropbox, for funding the mypy core team.

Thanks to all mypy contributors who contributed to this release:

  • Abtin
  • Brad Solomon
  • Chetan Khanna
  • Claudio Jolowicz
  • davidzwa
  • Diego Elio Pettenò
  • dosisod
  • Ethan Smith
  • Felicián Németh
  • Jelle Zijlstra
  • Jens Widell
  • Joy Bhalla
  • LiuYuhui
  • Markus Schmaus
  • Marten Kenbeek
  • Mattwmaster58
  • Max R
  • oda
  • pando
  • PattenR
  • prostomarkeloff
  • Shantanu
  • Steve Dignam
  • Timofey Kukushkin
  • Ville Skyttä
  • Xuanda Yang

Additional thanks to all contributors to typeshed:

  • Alex McGrath Kraak
  • Alexandre Yang
  • Andrew
  • Andrew Svetlov
  • Anis
  • Anthony Sottile
  • Ben Leslie
  • Ben Motz
  • Benjamin Poirier
  • Brian Turek
  • Bruce Merry
  • Christopher Whelan
  • coiax
  • David Euresti
  • David T.H. Kao
  • Debjyoti Biswas
  • Denis Laxalde
  • Diego Elio Pettenò
  • dosisod
  • Ethan Smith
  • Florian Ludwig
  • Florimond Manca
  • Gal Ben David
  • Graham Bleaney
  • Jakub Stasiak
  • Jan Verbeek
  • Jaromir Latal
  • Javier Honduvilla Coto
  • Jeff Hunter
  • Jelle Zijlstra
  • Jia Chen
  • Jocelyn Boullier
  • Joost Cassee
  • Julian Andres Klode
  • Julin S
  • karl ding
  • Katelyn Gigante
  • Kazushi Kitaya
  • Kjell Braden
  • Lars
  • Lawrence
  • Luciano Ramalho
  • Mark Mendoza
  • Markus Wamser
  • Max R
  • Mickaël Schoentgen
  • Nguyễn Gia Phong
  • Nipunn Koorapati
  • Oleg Höfling
  • Paul Ganssle
  • Peter Pentchev
  • petsuter
  • PGijsbers
  • Philipp Hahn
  • Rahix
  • Ran Benita
  • Razzi Abuissa
  • Rebecca Chen
  • Rodrigo Castro
  • Rune Tynan
  • Sahith Nallapareddy
  • Sam Bull
  • Sebastian Rittau
  • Selim Belhaouane
  • Serhiy Storchaka
  • Shantanu
  • Steve Dignam
  • Tim Hatch
  • Vishal Kuo
  • Zhiming Wang

Tuesday, 10 March 2020

Mypy 0.770 Released

We’ve just uploaded mypy 0.770 to the Python Package Index (PyPI). Mypy is a static type checker for Python. This release includes new features, bug fixes and library stub (typeshed) updates. You can install it as follows:

    python3 -m pip install -U mypy

You can read the full documentation for this release on Read the Docs.

Tagged Unions

Previously, the only way to distinguish between two types in a union was to use an isinstance check. Now, mypy supports distinguishing between two or more types based on the value of some common shared "tag" field.

This feature is most useful when you want to narrow down a union of TypedDicts: since TypedDicts are really just regular dicts at runtime, using isinstance checks won't work. Instead, you can now label or tag each TypedDict with a distinct Literal type and discriminate by checking that tag:

    from typing import Literal, TypedDict, Union
    
    class NewJob(TypedDict):
        event_type: Literal["new-job"]
        job_description: str
    
    class CancelJob(TypedDict):
        event_type: Literal["cancel-job"]
        job_id: int
    
    request: Union[NewJob, CancelJob]
    
    # We know request["event_type"] must be of type
    # Union[Literal["new-job"], Literal["cancel-job"]]
    if request["event_type"] == "new-job":
        # So if we narrow request["event_type"] down to type
        # Literal["new-job"], mypy will conclude 'request' must
        # therefore be of type 'NewJob' in this branch...
        print("Starting new job", request.job_description)
    else:
        # ...and inferred to be type 'CancelJob' in this one
        print("Cancelling job with id", request.job_id)

Note that you can import Literal from typing_extensions on Python 3.7 and earlier.

You can also use this technique to discriminate between unions of objects, tuples, or named tuples, so long as: 1. Every item in your union is tagged with a unique value 2. Mypy understands how to narrow the union of the tag values.

For more details and examples, see the documentation on tagged unions.

This feature was contributed by Michael Lee.

Type Inference Improvements

Type inference is now more powerful. Mypy can infer types in some cases where you previously needed an explicit type annotation.

Mypy can infer a built-in collection type from augmented assignment statements:

    x = []
    x += [1, 2]  # Infer type List[int] for x

Some dictionary construction idioms are better supported:

    d = {}  # No type annotation needed
    for k in things():
        if k not in d:
            d[k] = 0
        else:
            d[k] += 1

Mypy is better at inferring defaultdict types:

    from collections import defaultdict
    
    d = defaultdict(list)
    d['foo'].append(1)  # Infer type DefaultDict[str, List[int]] for d

Multiple Inheritance and isinstance() Checks

Previously, mypy assumed a variable cannot have two unrelated types when analyzing isinstance checks. For example, in the following example B is not a subclass of A, so mypy would incorrectly conclude the isinstance check is always false, and that the if-branch is unreachable — even though var could actually be a subtype of both types.

This meant that mypy skipped type checking anything inside the if statement, since it (by design) skips analyzing unreachable branches.

    class A: pass
    class B: pass
    
    class Ok(A, B): pass
    
    x: A = Ok()
    if isinstance(x, B):
        reveal_type(x)

Now, mypy will instead decide that the narrowed type of x is test.<subclass of "A" and "B">, instead of marking the branch as unreachable.

If it’s impossible for two types to be a subtype of one another, mypy will continue to not attempt to infer this "ad-hoc intersection":

    # Fails with a "TypeError: multiple bases have instance lay-out confict" error at runtime
    class Impossible(int, str): pass
    
    bad: int = Impossible()
    if instance(bad, str):
        # This branch is unreachable and so is not type checked.
        # If you want to be warned about unreachable branches, use
        # the --warn-unreachable flag.
        reveal_type(bad)

This feature was contributed by Michael Lee.

Other Notable Improvements and Bug Fixes

  • Fix some crash bugs involving import * and import cycles (PR 8450)
  • Fix interaction of descriptor methods with plugins (Jan Verbeek, PR 8365)
  • Allow strict in config file (Ville Skyttä, PR 8192)
  • Don’t crash when a module shadows builtin libraries (such as typing or types, PR 8405)
  • Fix type join between subclasses of unicode and str (PR 8402)
  • Fix type join of fixed-length tuples with mismatching lengths (Marti Raudsepp, PR 8333)
  • Fix type join of Sequence (e.g. variadic tuple) and fixed-length tuple (Marti Raudsepp, PR 8335)
  • Make mypy.api.run_dmypy actually capture the output (PR 8375)
  • Support determining whether a literal is truthy (Jan Verbeek, PR 8368)
  • Fix covariant overriding of decorated methods (Xuanda Yang, PR 8350)
  • Support typing.Annotated in addition to typing_extensions.Annotated (Jakub Stasiak, PR 8371)
  • Add add_method_to_class function to plugins.common (useful when writing mypy plugins) (Maksim Kurnikov, PR 8245)
  • Fix module alias as instance attribute (Uwe L. Korn, PR 8259)
  • Automatically write a file .gitignore file to cache directory, ignoring everything (Ville Skyttä , PR 8193)
  • Don't make dunder attributes enum members (Xuanda Yang, PR 8302)
  • Allow redefining TypedDict keys (while still generating an error) (Cohen Karnell, PR 8109)
  • Fix some crashes in dataclasses (PR 8271)
  • Use TypedDict union as type context when unambiguous (PattenR, PR 8212)
  • Fix false positive for subclasses of bytes overriding __str__ (Shantanu, PR 8222)
  • Fix deeply nested InitVar definitions in dataclasses with init=False (Jacob Beck, PR 8208)
  • Narrow types for walrus assignment in if statements in some cases (Shantanu, PR 8258)
  • Narrow types for walrus assignment in if statements in most of the rest of cases (PR 8458)
  • Fix incorrect error code indexing (Xuanda Yang, PR 8248)
  • Fix regression in container check logic (Michael Lee, PR 8232)
  • Make reachability code understand chained comparisons (Michael Lee, PR 8148)
  • Fix incorrect name lookup for decorated methods (Xuanda Yang, PR 8175)
  • Fix simplifying unions with type aliases (Xuanda Yang, PR 8146)
  • Fix crash when overriding __init__ in a dataclass subclass (Jacob Beck, PR 8159)
  • Fix some daemon crashes involving classes becoming generic (PR 8157)

Documentation and Error Reporting Improvements

  • Use fully qualified names in error messages for class names resembling builtins(Mukuntha N S, PR 8425)
  • Improve diagnostics involving missing stubs for a library that is installed in site-packages (Michael Lee, PR 8238)
  • Add a section to the documentation about incompatible overrides (RAHUL RAJA, PR 8377)
  • Add variable-sized tuples to the cheat sheet (Marcio Mazza, PR 8364)
  • Improve documentation of decorators (add decorator factories) (Marti Raudsepp, PR 8336)
  • Update documentation of variables and aliases (Xuanda Yang, PR 8200)
  • Report an error if a final class has abstract attributes (Denys Halenok, PR 8332)
  • Update common issues to include __init__ without arguments (Tan Yuanhong, PR 8303)
  • Add a new error code for errors about unreachability (Denys Halenok, PR 8312)
  • Fix error indicator position in code with tabs (dosisod, PR 8307)
  • Document --local-partial-types (Xuanda Yang, PR 8201)
  • Update documentation for Literal types (Michael Lee, PR 8152)

Stubtest rewrite

stubtest is a tool that compares stub definitions to what it finds at runtime with introspection and reports back inconsistencies. It got a complete rewrite. Some features of the new stubtest are:
  • Find missing, extraneous or mistyped classes, methods, functions and attributes in the stubs
  • Check presence, names and kinds of function arguments, accounting for overloads, decorators, *args and kwargs. Checks argument types against their default values, accounting for type vars.
  • Checks @property, @classmethod, @staticmethod declarations
  • Check types of module level and class level attributes and enums

Some results of this:

  • We now run stubtest in typeshed CI (for stdlib)
  • We’ve fixed about 1900 issues in typeshed definitions
  • We’ve greatly improved Python 3.8 support in typeshed and it’ll be easier to make the changes needed for future Python versions
  • We’ve uncovered a handful of issues in Python itself

The stubtest rewrite was contributed by Shanatu.

Typeshed Updates

Many small improvements were made to typeshed — too many to list. Browse the typeshed commit log here.

Acknowledgments

First of all, we’d like to thank our employer, Dropbox, for funding the mypy core team.

Thanks to all mypy contributors who contributed to this release:

  • Anthony Sottile
  • Cohen Karnell
  • Denys Halenok
  • dosisod
  • Ethan Smith
  • FooTaGe
  • hauntsaninja
  • HeShan
  • Jacob Beck
  • Jakub Stasiak
  • Jan Verbeek
  • Jérome Perrin
  • lazytype
  • Maksim Kurnikov
  • Marcio Mazza
  • Marti Raudsepp
  • Michael Lee
  • Mukuntha N S
  • Nikita Sobolev
  • PattenR
  • RAHUL RAJA
  • Shantanu
  • Tan Yuanhong
  • Uwe L. Korn
  • Ville Skyttä
  • Xuanda Yang

Additional thanks to all contributors to typeshed:

  • abe
  • Alan Du
  • Alex Grönholm
  • Alex Willmer
  • Andrew Svetlov
  • Anthony Sottile
  • Artjoms Iskovs
  • Batuhan Taşkaya
  • Benjamin Peterson
  • Brian Maissy
  • Cal Paterson
  • Christopher Dignam
  • crusaderky
  • Cyril Roelandt
  • Daniel Däschle
  • Daniel Farley
  • Daniel Hahler
  • Daniël van Eeden
  • Dave Halter
  • dave-shawley
  • Erick
  • Faidon Liambotis
  • Fionn Fitzmaurice
  • François Freitag
  • Gisle Aas
  • hauntsaninja
  • Ian Good
  • ijl
  • Ilaï Deutel
  • Jacob Beck
  • Jacob Ilias Komissar
  • Jakub Stasiak
  • Jan Verbeek
  • Jaromir Latal
  • Jason
  • Jason Gilholme
  • Jelle Zijlstra
  • Jens Hedegaard Nielsen
  • Jeppe Fihl-Pearson
  • layday
  • lazytype
  • Maarten ter Huurne
  • Mark
  • Michael Heyns
  • Mickaël Schoentgen
  • Niklas Fiekas
  • Oleg Höfling
  • Ophir LOJKINE
  • Pavel Savchenko
  • Rebecca Chen
  • Reid Swan
  • rikhilraithatha
  • Romain
  • Rune Tynan
  • Sebastian Rittau
  • Shantanu
  • Squirrel
  • Thomas Schaper
  • tikki
  • Vury Leo
  • Wolf Honore

Tuesday, 17 December 2019

Mypy 0.760 Released

We’ve just uploaded mypy 0.760 to the Python Package Index (PyPI). Mypy is a static type checker for Python. This release includes new features, bug fixes and library stub (typeshed) updates. You can install it as follows:

    python3 -m pip install -U mypy

You can read the full documentation for this release on Read the Docs.

Type Signature Suggestions for Tools

Normally mypy only infers the types of variables, and you have to explicitly annotate functions. Mypy daemon can now generate a suggestion for a function or method signature using static analysis through dmypy suggest. This is a low-level feature that can be used by other tools and editor integrations to make it easier to annotate existing code. See the documentation for more information.

Type Inference Improvements

Mypy type inference got a few minor improvements. Mypy can now infer a variable with a collection type from two assignments:

    items = []  # No type annotation needed
    if check():
        items = [2, 3]

Previously mypy required a type annotation for items. Mypy can also more often infer an OrderedDict type:

    from collections import OrderedDict

    data = OrderedDict()  # No type annotation needed
    data['key'] = 4

Mypy can infer the type of an attribute in more cases when it’s first initialized through self.x:

    class Counts:
        def __init__(self, n: int) -> None:
            self.counts = {}  # Type inferred from initialization
            for i in range(n):
                self.counts[i] = 0

Fixes to Regressions

  • Fix regression introduced in 0.750: union (non-)simplification should not affect type inference (PR 8095)

Breaking Changes

  • Make the error code of a binary operation involving overload operator, for consistency (PR 8124)

Other Notable Improvements and Bug Fixes

  • Generate error when assigning an Enum or TypedDict type to an attribute (Xuanda Yang, PR 8107)
  • Fix relative path calculation if path is on a different drive on Windows (Netzeband, PR 8094)
  • Don’t infer an abstract type object type from concrete type object values (Xuanda Yang, PR 8096)
  • Fix an inconsistency with type checking lambda expressions (PR 8080)
  • Fix crash involving generic callable types (PR 8075)
  • Improve error message with long tuple initializer (Xuanda Yang, PR 7995)
  • Improve mypy daemon documentation (PR 8041)
  • Recommend typing_extensions instead of mypy_extensions for TypedDict (PR 8023)
  • Fix an inconsistency with self types (PR 8030, PR 8021)
  • Support type alias within Literal[...] (Xuanda Yang, PR 8014)
  • Fix --warn-return-any false positive when returning Any from a function declared to return object (Xuanda Yang, PR 8011)
  • Stubgen: Split @abstractproperty into @abstractmethod and @property (Xuanda Yang, PR 8066)
  • Stubgen: Give a better error message when using a .pyd file as target (Xuanda Yang, PR 8063)
  • Update stubgen documentation (PR 8031)

Typeshed Updates

Many small improvements were made to typeshed — too many to list. Browse the typeshed commit log here.

Acknowledgments

First of all, we’d like to thank our employer, Dropbox, for funding the mypy core team.

Thanks to all mypy contributors who contributed to this release:

  • jag426
  • Netzeband
  • Xuanda Yang

Additional thanks to all contributors to typeshed:

  • Alois Klink
  • Benjamin Peterson
  • cshesse
  • Denis Eliseev
  • Dylan Anthony
  • Eugene Ha
  • hauntsaninja
  • Jacob Ilias Komissar
  • Jason Fried
  • Jelle Zijlstra
  • Katelyn Gigante
  • Maksim Kurnikov
  • Michał Słapek
  • Mohammed El-Afifi
  • Ran Benita
  • Robert Schweizer
  • Rune Tynan
  • Ryan Hileman
  • Sebastian Rittau
  • Steven Kalt
  • toppk
  • Tuomas Suutari

Friday, 29 November 2019

Mypy 0.750 Released

We’ve just uploaded mypy 0.750 to the Python Package Index (PyPI). Mypy is a static type checker for Python. This release includes many features, bug fixes and library stub (typeshed) updates. You can install it as follows:

    python3 -m pip install -U mypy

You can read the full documentation for this release on Read the Docs.

More Powerful Self-types

This version adds support for more patterns involving explicit annotations on self argument in methods. In particular, the mixin pattern got basic support via a protocol as a self annotation that specifies what the mixin expects from any class that subclasses it:

    class Lockable(Protocol):
        @property
        def lock(self) -> Lock: ...
    
    class AtomicCloseMixin:
        def atomic_close(self: Lockable) -> int:
            with self.lock:  # This is OK
                ... # perform some actions
    
    class File(AtomicCloseMixin):
        def __init__(self) -> None:
            self.lock = Lock()
    
    class Bad(AtomicCloseMixin):
        pass
    
    f = File()
    b = Bad()
    f.atomic_close()  # OK
    b.atomic_close()  # Error: Invalid self type for "atomic_close"

Another somewhat common pattern that got support via explicit self-types is overloaded generic constructors (in particular in library stubs):

    from typing import Any, AnyStr, Generic
    from typing_extensions import Literal
    
    class File(Generic[AnyStr]):
        @overload
        def __init__(self: File[bytes], raw: Literal[True]) -> None: ...
        @overload
        def __init__(self: File[str], raw: Literal[False]) -> None: ...
        @overload
        def __init__(self: File[Any], raw: bool = ...) -> None: ...
    
    reveal_type(File())  # type is File[Any]
    reveal_type(File(raw=True))  # type is File[bytes]

Read the docs for more examples and use cases.

Stubgen Revamped

Stubgen, the automatic stub generator that comes with mypy, has many fixes and improvements. In particular:

  • Recover from various errors that broke stub generation previously, such as inconsistent MROs or modules that crash on import.
  • Export imported names that aren't referenced in the module.
  • Export all names imported from the current package by default. Use --export-less to disable this behavior.
  • Fix various issues that resulted in syntactically invalid stubs being generated.
  • Fix signatures of various C extension methods.
  • Make the docstring parser more robust.
  • Add various heuristics to skip internal modules, such as tests and vendored packages.
  • Allow tweaking the level of logging. Add --verbose and --quiet flags.

Generating stub files has never been so easy and robust! Please read more docs here and try it on the libraries you maintain or use that don’t yet have stubs in Typeshed. Please consider contributing any stubs you create to Typeshed so that the community can share and improve them.

Mypy Daemon is No Longer Experimental

The mypy daemon has been the default way of running mypy locally at Dropbox for well over a year and it's quite stable. It also got several additional commands and flags for better customization (and existing flags got better documentation). In particular, mypy daemon now supports basic integration with external file system event watchers for even faster, sub-second type checking results over tens of thousands of files.

Use dmypy recheck --update FILE and dmypy recheck --remove FILE to directly tell the daemon which files got edited/deleted to avoid waiting for the built-in file system watcher. For more details, see the docs.

Static Inference of Annotations (Experimental)

The mypy daemon now supports (as an experimental feature) statically inferring a draft type annotation for a given function or method. Running dmypy suggest FUNCTION will produce a suggested signature in this format:

    (param_type_1, param_type_2, ...) -> ret_type

This is a low-level command that can be used by editors, IDEs, and other tools, such as the mypy plugin for PyCharm, to propose an annotation to the user, and/or to insert an annotation to a source file.

In this example, the function format_id() has no annotation:

    def format_id(user):
        return "User: {}".format(user)
    
    root = format_id(0)

Mypy uses call sites and return statements to infer that format_id() accepts an int and returns a str. For more details, see the docs.

Other Notable Improvements and Bug Fixes

  • Show closest candidates for misspelled module attributes (Theodore Liu, PR 7971)
  • Fix C string encoding in the mypyc compiler (Saleem Rashid, PR 7978)
  • Fix type-checking decorated generic methods (beezee, PR 7933)
  • Make revealed type of final variables distinct from non-final ones (Michael Lee, PR 7955)
  • Fix issubclass() to narrow down types of type variables (Xuanda Yang, PR 7930)
  • Refine types of parent expressions when narrowing expression types (Michael Lee, PR 7917)
  • Fix starting compiled mypy daemon on Windows (PR 7929)
  • Show closest candidates for misspelled keyword arguments (Martijn Wuis, PR 7888)
  • Fix type checking of ternary expressions with an empty collection (Xuanda Yang, PR 7892)
  • Support negative integers in literal types (Xuanda Yang, PR 7878)
  • Make sure type inference works for literals against protocols (PR 7882)
  • Don't add coercions when compiling expression statements via mypyc (jag426, PR 7872)
  • Fix crashes in mypy daemon when sorting union items (PR 7842)
  • Enable whole-file # type: ignore comments in Python 2.7 (Brandt Bucher, PR 7789)
  • Record internal Any types as precise in HTML report generator (ahmadF, PR 7708)
  • Add misc/dump-ast.py script to dump parse trees (Michael Wayne Goodman, PR 7820)
  • Use union component as a self-type in class methods (PR 7822)
  • Correctly handle union types in string interpolation checker (Vincent Barbaresi, PR 7809)
  • Fix capturing stderr in mypy.api.run (David Tucker, PR 7804)
  • Fix internal error when checking dataclasses with a duplicate field (Vincent Barbaresi, PR 7808)
  • Add cross references to mypy command line options in the documentation (Oleg Höfling, PR 7784, PR 7801, PR 7802)
  • Improve missing import error message (Lewis Cowles, PR 7698)
  • Add option to print absolute file paths (Maxim Koltsov, PR 7754)
  • Recommend using string escaping for classes that are non-generic at runtime (Rubin Raithel, PR 7707)
  • Fix accessing unannotated implicit class methods (PR 7739)
  • Ensure that non-total TypedDicts can be false (henribru, PR 7745)
  • Fix type checking __init_subclass__() (PR 7723)

Plugin API Changes and Improvements

This release includes three major mypy plugin API changes:

  • There is a new plugin hook for specifying per-module configuration data: report_config_data(). It can be used if the plugin has some sort of per-module configuration that can affect type checking.
  • *(breaking change)* New TypeAliasType type has been added and is now used for type aliases instead of eagerly expanding them. To get the expanded type use mypy.types.get_proper_type(). See this comment for more compatibility instructions.
  • *(breaking change)* Symbol node methods .fullname() and .name() were replaced with properties. See this comment for compatibility instructions.

These improvements are related to plugins:

  • Invoke the get_dynamic_class_hook() plugin hook also on method calls (Seth Yastrov, PR 7990)
  • Fix plugin invocation on class method calls through Type[...] (PR 7969)
  • Allow new plugins to be added by programs (like mypyc) that directly invoke build (PR 7875)

For more information on plugin hooks see the docs. Breaking API changes are announced in this GitHub issue. Please subscribe to it if you are an active mypy plugin developer.

Typeshed Updates

Many small improvements were made to typeshed — too many to list. Browse the typeshed commit log here.

Acknowledgments

First of all, we’d like to thank our employer, Dropbox, for funding the mypy core team.

Thanks to all mypy contributors who contributed to this release:

  • ahmadF
  • Alexandre Viau
  • beezee
  • Bob Whitelock
  • Brandt Bucher
  • Chad Dombrova
  • Daniel Hahler
  • David Euresti
  • David Tucker
  • Djedouas
  • Ekin Dursun
  • Emmanuel Nosa Evbuomwan
  • Ethan Smith
  • Gábor Lipták
  • henribru
  • hoefling
  • Ilaï Deutel
  • jag426
  • Lewis Cowles
  • Maxim Koltsov
  • Michael Lee
  • Michael R. Crusoe
  • Michael Wayne Goodman
  • Rubin Raithel
  • Saleem Rashid
  • Sebastian Rittau
  • Seth Yastrov
  • TH3CHARLie
  • Theodore Liu
  • Thomas Hisch
  • Tim Gates
  • Tudor Brindus
  • Tuomas Suutari
  • Vasily Zakharov
  • Vincent Barbaresi
  • Wuisch
  • Xuanda Yang
  • Zac Hatfield-Dodds

Additional thanks to all contributors to typeshed:

  • Alexander Schlarb
  • Angela Ambroz
  • Anthony Sottile
  • Árni Már Jónsson
  • Benjamin Peterson
  • bianca rosa
  • Brett Cannon
  • Christopher Hunt
  • cptpcrd
  • Daniel Hahler
  • David Tucker
  • Denis Laxalde
  • Diego Elio Pettenò
  • Dima Boger
  • Eric N. Vander Weele
  • Florian Bruhin
  • Greg Ward
  • Ilaï Deutel
  • Jakub Stasiak
  • Jelle Zijlstra
  • Jeremy Lainé
  • Jon Dufresne
  • JR Heard
  • Lawrence Chan
  • Maarten ter Huurne
  • Markus Bauer
  • Martijn Pieters
  • Martin DeMello
  • Michael Lee
  • Michael Seifert
  • Michał Słapek
  • Nathaniel Brahms
  • Nikita Sobolev
  • Nikola Forró
  • Ran Benita
  • Rebecca Chen
  • Rune Tynan
  • Ryan Morshead
  • Sebastian Rittau
  • Taneli Hukkinen
  • Trim21
  • Utkarsh Gupta
  • Vasily Zakharov
  • 秋葉

Wednesday, 16 October 2019

Mypy 0.740 Released

Mypy 0.740 Released

We’ve just uploaded mypy 0.740 to the Python Package Index (PyPI). Mypy is a static type checker for Python. This release includes many features, bug fixes and library stub (typeshed) updates. You can install it as follows:

    python3 -m pip install -U mypy

You can read the full documentation for this release on Read the Docs.

Type Checking for str.format Calls

Calls to the format method on string literals are now type-checked based on the rules of the format string syntax and the format specification mini-language (PR 7418)

This also fixes some corner cases in % formatting and allows flagging bad interactions between bytes and strings.

Here are some errors mypy can now catch:

  • Likely accidental formatting of bytes ("{}".format(b'123') will produce "b'123'" on Python 3 which is likely unintended — the !r specifier should be used when it is intended)
  • Invalid format string syntax
  • Invalid conversion type or specifier
  • Incorrect number of arguments or field names (One thing this will complain about is too many arguments for a format string—this does not cause an exception at runtime but is still usually a bug.)
  • Type mismatches for numeric formatting
  • Type errors in index or attribute expressions

Improved check_untyped_defs

The self argument to methods without annotations is now correctly given the object’s type (instead of Any) when using check_untyped_defs (PR 7530).

This allows substantially better checking of untyped methods as well as enabling inference of attribute types in some situations where they would not have been determined in the past.

Additionally, we now suppress most “needs type annotation” errors caused by assigning empty collections (i.e, data = []), in untyped functions.

More Precise Error Locations (Breaking Change)

Reported line and column numbers are now more precise; in particular, incompatible assignment errors are now reported as being an error with the right hand side rather than the left hand side (PR 7578, PR 7569).

In some cases these changes can break # type: ignores, but from our experience they don’t do it too often.

Stricter Treatment of Context Manager Objects

Mypy 0.730 added support for using Literal types in the return type from __exit__ to determine whether it is possible for a with statement to swallow exceptions, which can affect whether mypy thinks code after a with statement is reachable.

To better pinpoint the source of issues caused by this, mypy now gives an error when __exit__ methods are declared to return bool but always return False. See the documentation for more information.

Documentation and Other Error Message Improvements

  • Add many cross-references to standard library to mypy docs (Oleg Höfling)
  • Update examples of mutable and non-mutable mapping in cheat sheet (Marco, Gorelli, PR 7620)
  • Fix syntax errors in code examples (Oleg Höfling, PR 7651)
  • Always report dmypy crashes to the client (ideally this fix will affect nobody, but…. 😉 , PR 7593)
  • Fix some notes not being ignored when using # type: ignore[code] (PR 7573)
  • Check syntax errors in # type: ignore[code] comments (PR 7460)
  • Fix incorrect error message when a positional argument is missing in a function with multiple default arguments (PattenR, PR 7547)
  • Fix message when second argument to isinstance is an alias to Any (Cohen Karnell, PR 7504)

Other Notable Improvements and Bug Fixes

  • Only return a declared type from __new__ if it is a subtype (PR 7372)
  • Give better types for pathlib.Path.open (Michael Lee, PR 7643)
  • Fix a crash on missing self with --check-untyped-defs (PR 7669)
  • Treat __class_getitem__ as an implicit class method, similar to __init_subclass__ (ahmadF, PR 7647)
  • Allow TypedDict key with literal type during construction (PR 7645)
  • Support NamedTuple class syntax in all stubs (Sebastian Rittau, PR 7646)
  • Support eq and order arguments to attr.s (David Euresti, PR 7619)
  • Fix some false positives when checking raise statements (Patrick Williams, PR 7515)
  • Fix spurious errors with inherited dataclasses in incremental mode (PR 7596)
  • Fix a crash in mypy daemon (PR 7543)
  • Type-check class keyword in __init_subclass__ calls (g.denis, PR 7452)
  • Fix crash related to __getattr__ and __call__ (Ekin Dursun, PR 7446)
  • Fix incremental mode crashes (PR 7499)

Typeshed Updates

Many small improvements were made to typeshed — too many to list. Browse the typeshed commit log here.

Acknowledgments

First of all, we’d like to thank our employer, Dropbox, for funding the mypy core team.

Thanks to all mypy contributors who contributed to this release:

  • ahmadF
  • Andrzej Górski
  • Brad
  • Cohen Karnell
  • David Euresti
  • Ekin Dursun
  • g.denis
  • hoefling
  • Jelle Zijlstra
  • John Reese
  • Marco Gorelli
  • Michael Lee
  • Michael R. Crusoe
  • Patrick Williams
  • PattenR
  • Sebastian Rittau

Additional thanks to all contributors to typeshed:

  • Alan Du
  • Alex Garbutt
  • Alex Jurkiewicz
  • Andrew Svetlov
  • Anthony Sottile
  • Árni Már Jónsson
  • Augusto Hack
  • Benjamin Peterson
  • Brad
  • brianjyoung
  • Carl Meyer
  • Colin Gilgenbach
  • Eric Traut
  • Glyph
  • herr kaste
  • hh-h
  • Jelle Zijlstra
  • Jeremy Lainé
  • jjmortensen
  • Lukáš Lalinský
  • Parth Sharma
  • Philippe F
  • plokmijnuhby
  • Rafi Blecher
  • Rebecca Chen
  • robertschweizer
  • Rune Tynan
  • Russ Allbery
  • Ryan Morshead
  • Sebastian Rittau
  • sinancepel
  • Stefan T
  • Utkarsh Gupta
  • Vasily Zakharov
  • wouter bolsterlee
  • 秋葉