Thursday 2 March 2017

Mypy 0.501 Released

We’ve just uploaded mypy 0.501 to PyPI. This release adds new features, bug fixes and library stub updates. You can install it as follows:

    python3 -m pip install --upgrade mypy

Note: Remember that the package name is now mypy (no longer mypy-lang).

Switch to New Parser

Mypy now uses the typed_ast parser by default, which is more correct and significantly faster. The old parser is available for now with --no-fast-parser, but we are planning to remove it in the next release. Previously you had to enable the new parser explicitly through --fast-parser.

Note that mypy 0.501 requires a new, backwards incompatible version of typed_ast (1.0.1 or higher). This should be taken care of automatically by the package dependencies if you install mypy using pip .

Default to Python 3.6 Mode

Supported Python 3.6 features are now enabled by default, such as variable annotations (PEP 526), f-strings (PEP 498), and underscores in numeric literals (PEP 515).

Simple Metaclasses

Mypy now supports simple metaclasses. Mypy can look up attributes and methods defined in the metaclass, but mypy still doesn’t understand more dynamic metaclass behavior. For example, this works now:

    class Meta(type):
        def __add__(self, x: str) -> str:
            return 'a' + x

    class C(metaclass=Meta):
        ...

    print(C + 'x')  # Okay

You can also use metaclasses in Python 2:

    ...

    class C(object):
        __metaclass__ = Meta

This was contributed by Elazar Gershuni with help from Tom Manderson.

Warn about Missing Return Statements by Default

The --warn-no-return flag is now on by default, which means mypy will warn about functions missing a return statement on one or more code paths, unless the function’s return type is None or Any. For example:

        def f(n: int) -> int:  # Missing return statement
            if n > 3:
                return n + 1

Mypy currently doesn’t warn about empty function bodies or bodies that only have an ellipsis (…), since these are sometimes used for abstract methods and aren’t necessarily a problem. The option can generate false positives if you rely on the implicit None return value when execution falls off the end of a function. This behavior can be disabled globally with --no-warn-no-return or on a per-module basis with the warn_no_return config option.

This was contributed by Reid Barton.

NoReturn

You can now annotate functions that never return using mypy_extensions.NoReturn. Mypy will check that those functions do, in fact, not return, and will understand that they cause code paths to never return when called. Mypy now also knows that certain library functions such as sys.exit() don’t return. For example:

    from mypy_extensions import NoReturn
    def bad_number() -> NoReturn:
        raise RuntimeError("Bad number.")

    def f(n: int) -> int:  # okay
        if n > 3:
            return n + 1
        else:
            bad_number()

Install mypy_extensions using pip to use NoReturn:

    python3 -m pip install --upgrade mypy-extensions  # For Python 3
    pip install --upgrade mypy-extensions  # For Python 2

Leaving Out Redundant Generic[T]

You can omit redundant Generic[T] in the base class list if you have another reference to T within base classes. For example, this now works:

    from typing import TypeVar, Iterable

    T = TypeVar('T')

    class MyCollection(Iterable[T]):
        ...
        def __iter__(self) -> Iterator[T]: ...

    def collection_to_list(c: MyCollection[int]) -> List[int]:
        return list(c)

For previous versions of mypy you would have needed to write the class definition like this:

    ...
    class MyCollection(Iterable[T], Generic[T]):
        ...

This was contributed by Ivan Levkivskyi.

Better Checking of Assignments in Class Body

Mypy finally can check if assignments within a class body are compatible with base classes. Now this will get flagged as an error:

    class A:
        x = 1

    class B(A):
        x = 'a'  # Error

This was contributed by TrueBrain.

Strict Mode

Mypy now has a strict mode which turns on most flags that add additional checks. Strict mode can be enabled with --strict. Some of these checks may be opinionated (like --strict-boolean). New checks will be added to strict mode over time.

Invertible Options

Most boolean flags can now be explicitly inverted. See mypy --help for the names of the inverted options. For example, the inverse of --disallow-untyped-defs is --allow-untyped-defs. This is useful when an option is enabled in the config file but you want to disable it for a specific run without editing the config file.

More New Features

  • Read configuration from setup.cfg if mypy.ini not present. (Dominik Miedziński)
  • Support type comments for with and for statements. (Alex Frieder)
  • Support type comments for async with and async for statements. (Alex Frieder)
  • Support E[<str>] when E is an Enum type.
  • Support @no_type_check in fast parser.
  • api.run now accepts a list of command-line arguments and returns a 3-tuple, including exit status. (Jacques de Hooge)
  • Add --strict-boolean flag that warns about non-bool values used as conditions. (Alex Frieder)
  • Add --warn-return-any flag that warns about returning a value with Any type. (lincolnq)
  • Add support for __getattribute__. (Jelle Zijlstra)
  • Issue warning for possibly malformed asserts. (Alex Frieder)
  • Make most fast parser errors non-fatal.
  • Improve fast parser error messages.
  • TypedDict improvements (TypedDict is still undocumented and experimental). (Ivan Levkivskyi)

Notable Bugs Fixed

  • Detect missing imports of List, Dict and Set. (Ivan Levkivskyi)
  • Don't complain about method override when the base class method has type Any. (Naomi Seyfer)
  • Fix stubgen crash on an extension module containing an alias of object. (Jelle Zijlstra)
  • Fix crash on access to local classes. (Ivan Levkivskyi)
  • Fix crash on expressions like "%d%d" % (*x,).
  • Generate errors on classmethod and staticmethod override conflicts. (Alex Frieder)
  • Fix crash on invalid type comments/annotations. (Ivan Levkivskyi)
  • Fix crash when assigning to a variable with a partial type. (Alex Frieder)
  • Treat varargs as valid context in default lambda argument. (Elazar Gershuni)
  • Always process modules/packages given with -m /-p.
  • Generate error when using deleted variable in a conditional. (Alex Frieder)
  • Make fast parser able to parse machine-generated code with deep nesting. (Łukasz Langa)
  • Fix bug with type variables defined in different scopes being treated as the same type variable. (with help from Ivan Levkivskyi)
  • Generate error on Any(...) which fails at runtime. (Alex Frieder)
  • Check for duplicate names in function definitions when using the fast parser. (Alex Frieder)
  • Disallow duplicate type comments/annotations in fast parser. (Alex Frieder)
  • Fix error context for indexed assignment with an annotation. (Jelle Zijlstra)
  • Fix return type of dict.get in strict optional mode.
  • Type check assert messages in fast parser. (Alex Frieder)
  • Fix warning about missing return statements in async def functions. (Jelle Zijlstra)
  • Order of union items no longer affects type sameness. (Alex Frieder)
  • Propagate inference type context through reveal_type for more precise revealed types.
  • Allow unicode docstrings in Python 2. (Jelle Zijlstra)
  • Fix several Python 2 bugs in fast parser.
  • Fix some additional crashes.

Other Changes

Acknowledgments

Thanks to all mypy contributors who contributed to this release:

  • Adrien Chauve
  • Alex Frieder
  • Brandon W Maister
  • Dominik Miedziński
  • Eduard-Cristian Stefan
  • Elazar Gershuni
  • Ivan Levkivskyi
  • Jacques de Hooge
  • Jelle Zijlstra
  • lincolnq
  • Łukasz Langa
  • Naomi Seyfer
  • Tom Manderson
  • TrueBrain
  • Wojciech Kaczmarek

Additional thanks to these contributors to typeshed:

  • 5j9
  • Adam Marszałek
  • Alex Frieder
  • Alexey (forestbiiird)
  • Andrey Vlasovskikh
  • aostiles
  • Avy Faingezicht
  • Bertrand Bonnefoy-Claudet
  • David Euresti
  • Dominik Miedziński
  • Dylan Jenkinson
  • Eklavya Sharma
  • Eric Moyer
  • Ethan (ethanhs)
  • Ivan Levkivskyi
  • Jelle Zijlstra
  • lincolnq
  • Lucas Wiman
  • Łukasz Langa
  • Matt Kimball
  • Matthias Kramm
  • Mike Patek
  • Mohab Usama
  • rchen152
  • Richard Hansen
  • Roy Williams
  • Russ Allbery
  • Sunghyun Hwang
  • syrrim
  • Tim Abbott
  • Tom Manderson
  • Tomasz Elendt
  • Valérian Rousset

— Jukka (on behalf of the rest of the mypy team: Guido, David and Greg)