Tuesday, 16 April 2019

Mypy 0.701 Released

We've just uploaded mypy 0.701 to PyPI. This is a bugfix release containing no new features, only fixes for some important bugs and regressions in the (default) mypyc-compiled version of 0.700. You can install it as follows:

    python3 -m pip install --upgrade mypy

Mypy Bugs Fixed

  • Fix a crash in mypyc-compiled stubgen (PR 6642)
  • Compile with a newer version of mypyc that fixes several memory leak bugs (PR 6642)

Wednesday, 3 April 2019

Mypy 0.700 Released: Up To 4x Faster

We’ve just uploaded mypy 0.700 to the Python Package Index (PyPI). Mypy is a static type checker for Python. This release switches to a compiled version of mypy, which is up to 4x faster than the previous release. It also 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 documentation for this release on Read the Docs.

Much Improved performance

We are now shipping a mypy binary compiled with mypyc by default, which is up to 4x faster than the interpreted version shipped previously. The compiled version has been available as a separate PyPI distribution for a while now, and this is first release where it’s installed by default. Mypyc is a compiler that compiles type-annotated Python modules into efficient CPython C extension modules.

Note that the legacy, optional mypy_mypyc package will not be updated any more. If you used the mypy_mypyc package for an earlier mypy release, you should uninstall it first, before updating to the new package (you can safely ignore this if don’t know what this is):

    python3 -m pip uninstall mypy_mypyc

The compiled version is supported on 64-bit macOS, Windows and Linux platforms (Python 3.5 and later). On other platforms an interpreted version is used instead, which doesn’t provide any performance improvement. The compiled version is mostly compatible with the interpreted version, but some mypy plugins may be incompatible with it. You can still install the interpreted version of 0.700 like this:

    $ python3 -m pip install --no-binary mypy -U mypy

Stricter Equality Checks

If you run mypy with --strict-equality, mypy will detect equality and in checks that are likely to always result in True or False, since the operand types are not overlapping. For example, it will warn about comparing a str value to a bytes value, which can never be equal. See the documentation for more information.

Python 3.4 Unsupported for Running Mypy

You can no longer run mypy using Python 3.4, since Python 3.4 has reached its end of life. You can still type check code that targets Python 3.4, and we have no plans to drop support for this.

Plugin System Improvements

  • Add a get_additional_deps() plugin hook to support django-stubs (PR 6598)
  • Use the get_attribute_hook() plugin hook for dynamic classes (lincolnq, PR 6371)

Other Improvements

  • Allow # type: ignore comments after type comments (Ethan Smith, PR 6591)
  • Don't resolve callable NamedTuple fields to their return type (Danny Weinberg, PR 6576)
  • Support indexing unions containing tuples (PR 6475)
  • Fix member access on generic classes (PR 6418)
  • Fix interaction of isinstance() with Type[...] (PR 6419)
  • Fixes to tuple fallback types (PR 6442)
  • Fix missing built-in type aliases (PR 6441)
  • Make processing mypy cache faster (PR 6405)
  • Add an experimental mechanism for avoiding hashing sources on mypy daemon start (PR 6389)
  • Add flag --skip-cache-mtime-checks to skip mtime checks on cache files (PR 6391)
  • Give a better error message (and don't crash) if there is bad JSON in the cache (Ethan Smith, PR 6277)
  • Stubgen: improvements to stubs generated from docstrings (Wiktor Niesiobędzki, PR 6368)

Typeshed Updates (Highlights)

Here are selected typeshed updates (there are many more):

  • orjson: Add new stub file (ijl, PR 2747)
  • bleach: Add new stub file (Sebastian Rittau, PR 2709)
  • pycurl: Support Python 3 (JinyuanShanghai, PR 2867)
  • pydoc: Support Python 3 (Rebecca Chen, PR 2873)
  • multiprocessing: Add multiprocessing.spawn submodule and multiprocessing.pool stubs (Sean McLemon, PR 2823)
  • builtins: Add isascii methods to str, bytes, and bytearray for Python 3.7 (Brandt Bucher, PR 2834)
  • builtins: Add missing BaseException.__suppress_context__ attribute (wouter bolsterlee, PR 2876)
  • platform: Add types to some cross-platform functions (Paul Dagnelie, PR 2781)
  • codecs: Support the errors argument in factory functions (Aymeric Augustin, PR 2752)
  • charset: Improve the stubs under Python 3 (Josh Morton, PR 2768)
  • asyncio: Fix signature of asyncio.create_server (Aymeric Augustin, PR 2763)
  • asyncio: Update asyncio.streams stub (Gleb Chipiga, PR 2845)
  • werkzeug: Some small tweaks (lincolnq, PR 2784)
  • urllib[2]: Add stubs for HTTP Handler classes in Python 2 urllib2 and Python 3 urllib.request (Michael Brandt, PR 2710)
  • urllib2: Add some annotations (Philipp Hahn, PR 2688)
  • cyaml: Add some missing annotations (秋葉, PR 2769)
  • calendar: Add itermonthdays3 and itermonthdays4, fix incorrect cssclass_today (Sean McLemon, PR 2825)
  • enum: Add underscore names (秋葉, PR 2822)
  • logging: Changed parameter name of several methods from 'lvl' to 'level' to match the implementation (Eric Traut, PR 2840)
  • attr: Update attr stubs to 19.1.0 (Gleb Chipiga, PR 2846)
  • ast: Support new features and node types introduced in Python 3.8 (PR 2859)
  • flask: Fix several types (Gabriel Corona, PR 2858)
  • webbrowser: Update signature of webbrowser.register for Python 3.7 (Cary Yang, PR 2865)
  • pdb: Add missing class Pdb (Rebecca Chen, PR 2872)
  • yaml: add full_load and full_load_all stubs (Christopher Dignam, PR 2892)

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
  • Bernát Gábor
  • Danny Weinberg
  • Ethan Smith
  • Jelle Zijlstra
  • lincolnq
  • Mark Mendoza
  • Michael
  • Michael Lee
  • oremanj
  • Richard Eames
  • Sean McLemon
  • Sebastian Rittau
  • Wiktor Niesiobędzki

Additional thanks to all contributors to typeshed:

  • Alun Champion
  • Andrew Svetlov
  • Antoine Fourmy
  • Aymeric Augustin
  • Benjamin Peterson
  • Bertrand Bonnefoy-Claudet
  • Brandt Bucher
  • Cary Yang
  • Chen Li
  • Christopher Dignam
  • Eric Traut
  • Gabriel Corona
  • Gleb Chipiga
  • herr kaste
  • Hynek Schlawack
  • ijl
  • Ingmar Steen
  • Jeff
  • Jelle Zijlstra
  • JinyuanShanghai
  • Josh Morton
  • Joshua Oreman
  • Lawrence Chan
  • lincolnq
  • Luke Granger-Brown
  • Mark Mendoza
  • Matt Robinson
  • Maxim Kurnikov
  • Michael Brandt
  • Nipunn Koorapati
  • Pascal Corpet
  • Paul Dagnelie
  • Philipp Hahn
  • Rebecca Chen
  • Sean McLemon
  • Sebastian Rittau
  • Tom Briggs
  • Utkarsh Gupta
  • Vasily Zakharov
  • William Ayd
  • wouter bolsterlee
  • yoshiyuho
  • Łukasz Hanuszczak
  • 秋葉
— Jukka Lehtosalo, on behalf of the mypy team

Friday, 1 March 2019

Extending mypy with plugins

Python is a famously dynamic language. It’s easy to write DSL-like frameworks that are hard to understand by static type checkers. Although with recent mypy features, such as protocols and literal types, and with basic metaclass and descriptor support, we can more often provide precise types, it’s still often hard to avoid false positives and negatives. To solve this problem, while avoiding the need for custom type system features for every framework, mypy supports a plugin system. Plugins are Python modules that provide callbacks (plugin hooks) that mypy will call when type checking classes and functions that interact with a library or framework. For example, such hooks can provide a more precise function return type that is otherwise hard to express, or auto-generate some methods in a class, to reflect the effects of a class decorator. To read more about plugin system architecture and for the full list of available hooks, see these docs.

Bundled plugins for standard library

Mypy comes with a default plugin for some builtin functions and classes, and the ctypes, contextlib, and dataclasses modules. It also includes a plugin for attrs (for historical reasons — it was the first third-party plugin written for mypy). These plugins allow mypy to infer more precise types and correctly type check code using these library features. To illustrate this, consider this snippet:

    from dataclasses import dataclass
    from typing import Generic, TypeVar
    
    @dataclass
    class TaggedVector(Generic[T]):
        data: List[T]
        tag: str
    
    position = TaggedVector([0, 0, 0], 'origin')

Above, get_class_decorator_hook() is called when analyzing the class definition. It adds autogenerated methods, including __init__(), to the class body. Mypy uses this generated constructor to correctly infer TaggedVector[int] as the type of position. As you can see, plugins work even with generic classes.

Here’s another snippet:

    from contextlib import contextmanager
    
    @contextmanager
    def timer(title: str) -> Iterator[float]:
        ...
    with timer(9000) as tm:
        ...

The get_function_hook() hook provides a precise return type for the contextmanager decorator, so that calls to the decorated function can be type-checked precisely. Mypy can now detect an error: the argument to timer() must be a string.

Combining plugins and stubs

In addition to relying on dynamic Python features, frameworks often have the challenge of having large APIs. Mypy needs stub files for the libraries to check code that uses those libraries (unless the library contains inline annotations, which is still often not the case). Distributing the stubs for large frameworks via typeshed is not very practical:

  • Typeshed has a relatively slow release cycle (it’s bundled with mypy).
  • Incomplete stubs can cause false positives that are hard to avoid.
  • There’s no easy way to mix and match stubs from different typeshed versions.
Stub packages, introduced in PEP 561, help with these issues:
  • Maintainers can release a stub package as often as they want.
  • Users who haven’t opted in to using the package won’t see any false positives.
  • You can freely install arbitrary versions of multiple different stub packages.

Moreover, pip allows combining stubs for a library and the corresponding mypy plugin into a single distribution. Stubs for a framework and a corresponding mypy plugin can now be easily developed and distributed together, which is often useful since plugins fill in missing or imprecise definitions in the stubs.

A recent example of such a package is SQLAlchemy stubs and plugin, the first public 0.1 release of which was published on PyPI earlier this month. Although the project is still in early alpha, we are already successfully using it at Dropbox to improve type checking precision. Currently the plugin understands basic ORM declarations:

    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy import Column, Integer, String
    
    Base = declarative_base()
    
    class User(Base):
        __tablename__ = 'users'
        id = Column(Integer, primary_key=True)
        name = Column(String)

In the above snippet, the plugin uses the get_dynamic_class_hook() hook to tell mypy that Base is a valid base class, even though it doesn’t look like one. Then get_base_class_hook() is called on the definition of User, and it adds some autogenerated attributes. Next we instantiate the model:

    user = User(id=42, name=42)

The get_function_hook() hook is called, so that mypy can spot the error here: an integer is given instead of a user name.

The stubs define Column as a generic descriptor, so that attributes on a model get correct types:

    id_col = User.id  # Inferred type is "Column[int]"
    name = user.name  # Inferred type is "Optional[str]"

We welcome PRs that add more precise types to the stubs (the progress for core modules is tracked here).

Here are some gotchas that we found while working on the stubs:

  • Use a module-level __getattr__() to avoid false positives during the very early stages, when stubs are incomplete (this suppresses mypy errors due to missing module attributes). You can also use it in __init__.py files if some submodules are missing.
  • Descriptors often help with giving more precise types for customized attribute access (like in the Column example above), and it’s OK to use them even if the actual runtime implementation uses a more complex mechanism involving a metaclass, for example.
  • Don’t hesitate to declare framework classes as generic in stubs. Although they are not generic at runtime, this often allows us to give much more precise types for certain framework features, while runtime errors can easily be worked around. (We hope that frameworks will gradually add built-in support for generic types by explicitly inheriting relevant classes from typing.Generic.)

Recently released mypy plugins

There are already several plugins available for some popular Python frameworks. Apart from the above mentioned plugin for SQLAlchemy, other notable recent examples of packages with stubs and a bundled mypy plugin include stubs for Django and Zope Interfaces. All these projects are under active development.

Installing and enabling plugin + stub packages

Use pip to install a package with a mypy plugin and/or stubs in the virtual environment where mypy is installed:

    $ pip install sqlalchemy-stubs

Mypy should automatically discover the installed stubs. To enable the plugins you’ve installed, explicitly include them in your mypy.ini (or a custom config file):

    [mypy]
    plugins = sqlmypy, mypy_django_plugin.main 

Developing mypy plugins and writing stubs

If you want to develop a stubs + plugin package for a framework you use, you can use the sqlalchemy-stubs repository as a template. It includes the setup.py file, testing infrastructure using data-driven tests, and an example plugin class with a bunch of plugin hooks. We recommend using stubgen, an automatic stub generator that comes with mypy, to get started with stubs. Stubgen got several improvements in mypy 0.670.

For more details about mypy plugin system, see the docs. You can also just browse the source code of the plugins mentioned above. If you have any questions, feel free to ask them on the Python typing Gitter chat.

Friday, 8 February 2019

Mypy 0.670 Released

We’ve just uploaded mypy 0.670 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

(There are also new mypy-mypyc wheels; see the 0.660 release blog post.)

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

New Feature: Variable Redefinition

As you might have experienced, PEP 484 and mypy require a variable to keep its initial type throughout a scope. Occasionally this can be annoying, as the traditional workaround is to rename the second (independent) use of the variable. We have introduced a new flag, --allow-redefinition, which relaxes this behavior in certain contexts. Here’s an example where this may be useful:

    def process(items: List[str]) -> None:
        # 'items' has type List[str]
        items = [item.split() for item in items]
        # 'items' now has type List[List[str]]
        ...

You can also enable this per module in the mypy.ini file using allow_redefinition = True. See the docs for the command-line flag and the config option.

Stubgen Improvements

We’ve done a fairly large overhaul of the stubgen utility, which can automatically generate draft stub files for almost any module or package:

  • Streamline the command-line interface; in particular, the source discovery/collection options now more closely resemble those of mypy itself: -m <module>, -p <package>, <file> or <directory>
  • Perform a lightweight semantic analysis to generate somewhat better stubs
  • Added documentation
  • When parsing types out of docstrings (this happens for C modules only), stubgen now handles overloaded signatures generated by pybind11 (Wiktor Niesiobędzki, PR 5975)

Other Improvements

  • Expand getting started docs to discuss type hints in more detail (Michael Lee, PR 6226)
  • Always infer in operator as returning bool (Joel Croteau, PR 5688)
  • Allow star args in ctypes.Array constructor (Alan Du, PR 6213)
  • Fix plugin invocation for __call__ methods (oremanj, PR 6334)
  • Implement the XDG directory spec for config files: $XDG_CONFIG_HOME/mypy/config is now included in the search path for config files (Ryan Delaney, PR 6304)
  • When using the --junit-xml flag, the Python version and platform in the junit.xml file are now formatted as mypy-py3_6-windows — previously this was mypy-py3.6-windows but the dot was misinterpreted by some tools (PR 6222)
  • Update the typed_ast dependency to version 1.3.1; this means we now officially support Python 3.7
  • Temporarily delete pyproject.toml from the repo in order to work around a pip bug (PR 6342)
  • Include mypy_bootstrap.ini in PyPI packages (John Reese, PR 6252)

Internal Improvements and Code Cleanup

  • Fix daemon overlapped I/O when more data needs to be read (Ethan Smith, PR 6272)
  • Move most message constants to mypy.message_registry (Chad Dombrova, PR 6194)
  • Fix all DeprecationWarning: invalid escape sequence (Mickaël Schoentgen, PR 6195)
  • Add strictness flags (for mypy itself) that can be added with no source code changes (Michael Lee, PR 6237)
  • Some daemon performance improvements for large code bases

Typeshed Updates

  • Create stubs for Flask (Pascal Corpet, PR 2740)
  • Fix type of indent in JSONEncoder (Vield, PR 2737)
  • Make metavar in argparse be Optional (cormoran, PR 2739)
  • As of Python 3.6 dump_stats() method allows PathLike object to be passed (Igor Davydenko, PR 2741)
  • Add back StopIteration.value in Python 3 (Jelle Zijlstra, PR 2744)
  • Fix logging.getLevelName() type hints (Michael Noseworthy, PR 2730)
  • Add missing explicit Optional to stubs for the xml.etree package (Michael R. Shannon, PR 2734)
  • logging: inherit TimedRotatingFileHandler from Handler (Евгений, PR 2738)
  • Add SSLCertVerificationError fields (Hynek Schlawack, PR 2745)
  • Fix six.raise_from() value type (Frazer McLean, PR 2746)
  • builtins.pyi: Update __iadd__() and __imul__() in class list (Utkarsh Gupta, PR 2754)
  • pkg_resources: Add PKG_INFO str attribute for Distribution class (Joachim Jablon, PR 2775)
  • pkg_resources: fix stub for get_metadata_lines() (Joachim Jablon, PR 2776)
  • Add type annotation for collections.deque.__iadd__() (Joel Rosdahl, PR 2774)

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:

  • Alan Du
  • Chad Dombrova
  • Ethan Smith
  • Joel Croteau
  • John Reese
  • Michael Lee
  • Mickaël Schoentgen
  • oremanj
  • Ryan Delaney
  • Sebastian Witowski
  • Wiktor Niesiobędzki

Additional thanks to all contributors to typeshed:

  • cormoran
  • Евгений
  • Frazer McLean
  • Hynek Schlawack
  • Igor Davydenko
  • Jelle Zijlstra
  • Joachim Jablon
  • Joel Rosdahl
  • Michael Noseworthy
  • Michael R. Shannon
  • Pascal Corpet
  • Utkarsh Gupta
  • Vield
— Guido van Rossum, on behalf of the mypy team

Wednesday, 16 January 2019

Mypy 0.660 Released

We’ve just uploaded mypy 0.660 to the Python Package Index (PyPI). Mypy is a static type checker for Python. This release includes an optional compiled version, 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 documentation for this release on Read the Docs.

Introducing an Optional Compiled Version of Mypy — mypy-mypyc

As part of our ongoing attempts to speed up mypy, we have built mypyc, an ahead-of-time compiler from type-annotated Python to CPython C extensions modules. We will be writing more about mypyc in the near future, but for now the main thing to know is that mypy can be compiled with mypyc, speeding it up by up to 3-4x!

To install a compiled mypy, instead of installing the mypy package, install the mypy-mypyc one (mypy-mypyc packages share version numbers with the corresponding mypy package):

    python3 -m pip uninstall -U mypy  # if mypy is installed
    python3 -m pip install -U mypy-mypyc

Binaries are available for 64-bit Windows, macOS, and Linux for Python 3.5 to 3.7.

Literal Types

This release introduces a new experimental kind of type: literal types. Literal types let you declare that some expression is equal to a specific primitive value. For example, if a variable is annotated with the type Literal["foo"], mypy will understand that variable is not only of type str, but is also equal to specifically the string "foo".

This feature is particularly useful when you want to annotate functions where the return type depends on the exact value provided. For example, suppose we have a function fetch_data(…) that returns bytes if the first argument is True, and str if it’s False. Previously, there was no good way of annotating the return type of fetch_data: the best we can do is Union[bytes, str]. With literal types, we can produce a more precise signature:

    from typing import overload
    from typing_extensions import Literal
    
    @overload
    def fetch_data(raw: Literal[True]) -> bytes: ...
    @overload
    def fetch_data(raw: Literal[False]) -> str: ...
    # Fallback overload if the user provides a regular bool
    @overload
    def fetch_data(raw: bool) -> Union[bytes, str]: ...
    
    def fetch_data(raw):
        # Implementation is omitted
        ...
    
    reveal_type(fetch_data(True))   # Revealed type is 'bytes'
    reveal_type(fetch_data(False))  # Revealed type is 'str'
Note 1: Literal types have some important nuances and limitations. For example, Literal[…] may contain only primitive literal values, and mypy will not attempt to understand complex expressions using literal types on a deep level. For more details, please see the documentation. Note 2: In order to use this feature, you must install the latest typing_extensions package, version 3.7.2:
    python3 -m pip install -U typing_extensions

Mypy Daemon Windows Support

Thanks to work from Ethan Smith, the mypy daemon, dmypy, is now fully supported on Windows!

Quick Mode Removed

The quick mode (--quick-and-dirty) has been deprecated for two mypy releases and has now been removed. The mypy daemon, dmypy, offers high speed without the correctness compromises of the quick mode.

Plugin Improvements

  • Add documentation for plugin system (PR 6057)
  • Make name lookup available to all plugin hooks (PR 6044)
  • Add more information to FunctionContext and MethodContext (Maxim Kurnikov, PR 5918)

Other Improvements and Notable Bugs Fixed

  • Introduce an optional sqlite backed incremental cache, enabled with --sqlite-cache (PR 6023)
  • Fix a daemon crash when there is a decode error (PR 6064)
  • Allow setting python_executable from config file (Ethan Smith, PR 5777)
  • Short-circuit if expression for always true/always false variables and MYPY/TYPE_CHECKING (Samer Masterson, PR 5965)
  • Don't map actual kwargs to formal *args (PR 6096)
  • Disable cache when producing reports (Maarten ter Huurne, PR 6076)
  • Fix issues with pointer arrays in the ctypes plugin (Jakub Stasiak, PR 6097)
  • Support kw_only=True in the attrs plugin (David Euresti, PR 6107)
  • Fix some daemon crash bugs (PR 6098)
  • Better error messages when __eq__ has unexpected signature (David Wobrock, PR 6106)
  • Collect additional timing stats and allow reporting them from the daemon (PR 6137)
  • Fix dmypy run when bad options passed to mypy (Ethan Smith, PR 6153)
  • Improve error messages from multiple inheritance compatibility checks (Maxim Kurnikov, PR 5926)
  • Fix an incremental mode crash that can occur in situations with import cycles and star imports (PR 6179)

mypy_extensions Moved to a Separate Repository

This is likely only of interest to downstream packagers, but the mypy_extensions module has been moved from the extensions subdirectory of the mypy repository to its own repository, https://github.com/python/mypy_extensions.

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:

  • Chad Dombrova
  • Chris Philip
  • David Euresti
  • David Wobrock
  • Ethan Smith
  • Jakub Stasiak
  • Jared Hance
  • Jonathan Striebel
  • Maarten ter Huurne
  • Maxim Kurnikov
  • Michael Lee
  • Mykhailo Havelia
  • Samer Masterson
  • Shashank Parekh
  • Vincent Perez

Additional thanks to all contributors to typeshed:

  • Alexander Lyon
  • Alex Sarkesian
  • Andrew Gaul
  • Andrew Svetlov
  • Brandt Bucher
  • Dan Čermák
  • Daniel Mouritzen
  • Dave Halter
  • David Euresti
  • Diogo Magalhães Martins
  • Dominik Gabi
  • Ethan Smith
  • gnattishness
  • Hynek Schlawack
  • Ilya Konstantinov
  • Jared Hance
  • Jelle Zijlstra
  • Juan Gonzalez
  • Kai Willadsen
  • Kostya Esmukov
  • Michael Lee
  • Philipp Hahn
  • Sander Voerman
  • Savo Kovačević
  • Sebastian Rittau
  • Tomer Keren
  • Utkarsh Gupta
  • Ville Skyttä
— Michael J. Sullivan, on behalf of the mypy team