Loading PKG-INFO +1 −1 Original line number Diff line number Diff line Metadata-Version: 2.1 Name: mypy Version: 0.641 Version: 0.650 Summary: Optional static typing for Python Home-page: http://www.mypy-lang.org/ Author: Jukka Lehtosalo Loading README.md +14 −0 Original line number Diff line number Diff line Loading @@ -250,6 +250,20 @@ tracker: Feel free to also ask questions on the tracker. mypy_mypyc ---------- We have built an experimental compiled version of mypy using the [mypyc compiler](https://github.com/mypyc/mypyc) for mypy-annotated Python code. It is approximately 4 times faster than interpreted mypy. If you wish to test out the compiled version of mypy, and are running OS X or Linux, you can directly install a binary from https://github.com/mypyc/mypy_mypyc-wheels/releases/latest. Compiled mypy packages on PyPI are Coming Soon. Help wanted ----------- Loading docs/source/cheat_sheet.rst +2 −2 Original line number Diff line number Diff line Loading @@ -204,8 +204,8 @@ that are common in idiomatic Python are standardized. def f(my_mapping): # type: (MutableMapping[int, str]) -> Set[str] my_dict[5] = 'maybe' return set(my_dict.values()) my_mapping[5] = 'maybe' return set(my_mapping.values()) f({3: 'yes', 4: 'no'}) Loading docs/source/class_basics.rst +180 −26 Original line number Diff line number Diff line Loading @@ -8,7 +8,7 @@ rules. Instance and class attributes ***************************** Mypy type checker detects if you are trying to access a missing The mypy type checker detects if you are trying to access a missing attribute, which is a very common programming error. For this to work correctly, instance and class attributes must be defined or initialized within the class. Mypy infers the types of attributes: Loading Loading @@ -38,8 +38,9 @@ a type annotation: a = A() a.x = [1] # OK As in Python generally, a variable defined in the class body can used as a class or an instance variable. As in Python generally, a variable defined in the class body can be used as a class or an instance variable. (As discussed in the next section, you can override this with a ``ClassVar`` annotation.) Type comments work as well, if you need to support Python versions earlier than 3.6: Loading Loading @@ -77,6 +78,98 @@ to it explicitly using ``self``: a = self a.x = 1 # Error: 'x' not defined Annotating `__init__` methods ***************************** The ``__init__`` method is somewhat special -- it doesn't return a value. This is best expressed as ``-> None``. However, since many feel this is redundant, it is allowed to omit the return type declaration on ``__init__`` methods **if at least one argument is annotated**. For example, in the following classes ``__init__`` is considered fully annotated: .. code-block:: python class C1: def __init__(self) -> None: self.var = 42 class C2: def __init__(self, arg: int): self.var = arg However, if ``__init__`` has no annotated arguments and no return type annotation, it is considered an untyped method: .. code-block:: python class C3: def __init__(self): # This body is not type checked self.var = 42 + 'abc' Class attribute annotations *************************** You can use a ``ClassVar[t]`` annotation to explicitly declare that a particular attribute should not be set on instances: .. code-block:: python from typing import ClassVar class A: x: ClassVar[int] = 0 # Class variable only A.x += 1 # OK a = A() a.x = 1 # Error: Cannot assign to class variable "x" via instance print(a.x) # OK -- can be read through an instance .. note:: If you need to support Python 3 versions 3.5.2 or earlier, you have to import ``ClassVar`` from ``typing_extensions`` instead (available on PyPI). If you use Python 2.7, you can import it from ``typing``. It's not necessary to annotate all class variables using ``ClassVar``. An attribute without the ``ClassVar`` annotation can still be used as a class variable. However, mypy won't prevent it from being used as an instance variable, as discussed previously: .. code-block:: python class A: x = 0 # Can be used as a class or instance variable A.x += 1 # OK a = A() a.x = 1 # Also OK Note that ``ClassVar`` is not a class, and you can't use it with ``isinstance()`` or ``issubclass()``. It does not change Python runtime behavior -- it's only for type checkers such as mypy (and also helpful for human readers). You can also omit the square brackets and the variable type in a ``ClassVar`` annotation, but this might not do what you'd expect: .. code-block:: python class A: y: ClassVar = 0 # Type implicitly Any! In this case the type of the attribute will be implicitly ``Any``. This behavior will change in the future, since it's surprising. .. note:: A ``ClassVar`` type parameter cannot include type variables: ``ClassVar[T]`` and ``ClassVar[List[T]]`` are both invalid if ``T`` is a type variable (see :ref:`generic-classes` for more about type variables). Overriding statically typed methods *********************************** Loading @@ -85,27 +178,35 @@ override has a compatible signature: .. code-block:: python class A: class Base: def f(self, x: int) -> None: ... class B(A): class Derived1(Base): def f(self, x: str) -> None: # Error: type of 'x' incompatible ... class C(A): class Derived2(Base): def f(self, x: int, y: int) -> None: # Error: too many arguments ... class D(A): class Derived3(Base): def f(self, x: int) -> None: # OK ... class Derived4(Base): def f(self, x: float) -> None: # OK: mypy treats int as a subtype of float ... class Derived5(Base): def f(self, x: int, y: int = 0) -> None: # OK: accepts more than the base ... # class method .. note:: You can also vary return types **covariantly** in overriding. For example, you could override the return type ``object`` with a subtype such as ``int``. Similarly, you can vary argument types example, you could override the return type ``Iterable[int]`` with a subtype such as ``List[int]``. Similarly, you can vary argument types **contravariantly** -- subclasses can have more general argument types. You can also override a statically typed method with a dynamically Loading @@ -120,50 +221,103 @@ effect at runtime: .. code-block:: python class A: class Base: def inc(self, x: int) -> int: return x + 1 class B(A): class Derived(Base): def inc(self, x): # Override, dynamically typed return 'hello' # Incompatible with 'A', but no mypy error return 'hello' # Incompatible with 'Base', but no mypy error Abstract base classes and multiple inheritance ********************************************** Mypy supports Python abstract base classes (ABCs). Abstract classes have at least one abstract method or property that must be implemented by a subclass. You can define abstract base classes using the ``abc.ABCMeta`` metaclass, and the ``abc.abstractmethod`` and ``abc.abstractproperty`` function decorators. Example: by any *concrete* (non-abstract) subclass. You can define abstract base classes using the ``abc.ABCMeta`` metaclass and the ``abc.abstractmethod`` function decorator. Example: .. code-block:: python from abc import ABCMeta, abstractmethod class A(metaclass=ABCMeta): class Animal(metaclass=ABCMeta): @abstractmethod def foo(self, x: int) -> None: pass def eat(self, food: str) -> None: pass @property @abstractmethod def bar(self) -> str: pass def can_walk(self) -> bool: pass class Cat(Animal): def eat(self, food: str) -> None: ... # Body omitted class B(A): def foo(self, x: int) -> None: ... def bar(self) -> str: return 'x' @property def can_walk(self) -> bool: return True a = A() # Error: 'A' is abstract b = B() # OK x = Animal() # Error: 'Animal' is abstract due to 'eat' and 'can_walk' y = Cat() # OK .. note:: In Python 2.7 you have to use ``@abc.abstractproperty`` to define an abstract property. Note that mypy performs checking for unimplemented abstract methods even if you omit the ``ABCMeta`` metaclass. This can be useful if the metaclass would cause runtime metaclass conflicts. Since you can't create instances of ABCs, they are most commonly used in type annotations. For example, this method accepts arbitrary iterables containing arbitrary animals (instances of concrete ``Animal`` subclasses): .. code-block:: python def feed_all(animals: Iterable[Animal], food: str) -> None: for animal in animals: animal.eat(food) There is one important peculiarity about how ABCs work in Python -- whether a particular class is abstract or not is somewhat implicit. In the example below, ``Derived`` is treated as an abstract base class since ``Derived`` inherits an abstract ``f`` method from ``Base`` and doesn't explicitly implement it. The definition of ``Derived`` generates no errors from mypy, since it's a valid ABC: .. code-block:: python from abc import ABCMeta, abstractmethod class Base(metaclass=ABCMeta): @abstractmethod def f(self, x: int) -> None: pass class Derived(Base): # No error -- Derived is implicitly abstract def g(self) -> None: ... Attempting to create an instance of ``Derived`` will be rejected, however: .. code-block:: python d = Derived() # Error: 'Derived' is abstract .. note:: It's a common error to forget to implement an abstract method. As shown above, the class definition will not generate an error in this case, but any attempt to construct an instance will be flagged as an error. A class can inherit any number of classes, both abstract and concrete. As with normal overrides, a dynamically typed method can implement a statically typed method defined in any base class, including an abstract method defined in an abstract base class. override or implement a statically typed method defined in any base class, including an abstract method defined in an abstract base class. You can implement an abstract property using either a normal property or an instance variable. docs/source/common_issues.rst +52 −0 Original line number Diff line number Diff line Loading @@ -382,6 +382,23 @@ More specifically, mypy will understand the use of ``sys.version_info`` and else: # Other systems As a special case, you can also use one of these checks in a top-level (unindented) ``assert``; this makes mypy skip the rest of the file. Example: .. code-block:: python import sys assert sys.platform != 'win32' # The rest of this file doesn't apply to Windows. Some other expressions exhibit similar behavior; in particular, ``typing.TYPE_CHECKING``, variables named ``MYPY``, and any variable whose name is passed to ``--always-true`` or ``--always-false``. (However, ``True`` and ``False`` are not treated specially!) .. note:: Mypy currently does not support more complex checks, and does not assign Loading Loading @@ -496,6 +513,41 @@ Here's the above example modified to use ``MYPY``: return [arg] Using classes that are generic in stubs but not at runtime ---------------------------------------------------------- Some classes are declared as generic in stubs, but not at runtime. Examples in the standard library include ``os.PathLike`` and ``queue.Queue``. Subscripting such a class will result in a runtime error: .. code-block:: python from queue import Queue class Tasks(Queue[str]): # TypeError: 'type' object is not subscriptable ... results: Queue[int] = Queue() # TypeError: 'type' object is not subscriptable To avoid these errors while still having precise types you can either use string literal types or ``typing.TYPE_CHECKING``: .. code-block:: python from queue import Queue from typing import TYPE_CHECKING if TYPE_CHECKING: BaseQueue = Queue[str] # this is only processed by mypy else: BaseQueue = Queue # this is not seen by mypy but will be executed at runtime. class Tasks(BaseQueue): # OK ... results: 'Queue[int]' = Queue() # OK .. _silencing-linters: Silencing linters Loading Loading
PKG-INFO +1 −1 Original line number Diff line number Diff line Metadata-Version: 2.1 Name: mypy Version: 0.641 Version: 0.650 Summary: Optional static typing for Python Home-page: http://www.mypy-lang.org/ Author: Jukka Lehtosalo Loading
README.md +14 −0 Original line number Diff line number Diff line Loading @@ -250,6 +250,20 @@ tracker: Feel free to also ask questions on the tracker. mypy_mypyc ---------- We have built an experimental compiled version of mypy using the [mypyc compiler](https://github.com/mypyc/mypyc) for mypy-annotated Python code. It is approximately 4 times faster than interpreted mypy. If you wish to test out the compiled version of mypy, and are running OS X or Linux, you can directly install a binary from https://github.com/mypyc/mypy_mypyc-wheels/releases/latest. Compiled mypy packages on PyPI are Coming Soon. Help wanted ----------- Loading
docs/source/cheat_sheet.rst +2 −2 Original line number Diff line number Diff line Loading @@ -204,8 +204,8 @@ that are common in idiomatic Python are standardized. def f(my_mapping): # type: (MutableMapping[int, str]) -> Set[str] my_dict[5] = 'maybe' return set(my_dict.values()) my_mapping[5] = 'maybe' return set(my_mapping.values()) f({3: 'yes', 4: 'no'}) Loading
docs/source/class_basics.rst +180 −26 Original line number Diff line number Diff line Loading @@ -8,7 +8,7 @@ rules. Instance and class attributes ***************************** Mypy type checker detects if you are trying to access a missing The mypy type checker detects if you are trying to access a missing attribute, which is a very common programming error. For this to work correctly, instance and class attributes must be defined or initialized within the class. Mypy infers the types of attributes: Loading Loading @@ -38,8 +38,9 @@ a type annotation: a = A() a.x = [1] # OK As in Python generally, a variable defined in the class body can used as a class or an instance variable. As in Python generally, a variable defined in the class body can be used as a class or an instance variable. (As discussed in the next section, you can override this with a ``ClassVar`` annotation.) Type comments work as well, if you need to support Python versions earlier than 3.6: Loading Loading @@ -77,6 +78,98 @@ to it explicitly using ``self``: a = self a.x = 1 # Error: 'x' not defined Annotating `__init__` methods ***************************** The ``__init__`` method is somewhat special -- it doesn't return a value. This is best expressed as ``-> None``. However, since many feel this is redundant, it is allowed to omit the return type declaration on ``__init__`` methods **if at least one argument is annotated**. For example, in the following classes ``__init__`` is considered fully annotated: .. code-block:: python class C1: def __init__(self) -> None: self.var = 42 class C2: def __init__(self, arg: int): self.var = arg However, if ``__init__`` has no annotated arguments and no return type annotation, it is considered an untyped method: .. code-block:: python class C3: def __init__(self): # This body is not type checked self.var = 42 + 'abc' Class attribute annotations *************************** You can use a ``ClassVar[t]`` annotation to explicitly declare that a particular attribute should not be set on instances: .. code-block:: python from typing import ClassVar class A: x: ClassVar[int] = 0 # Class variable only A.x += 1 # OK a = A() a.x = 1 # Error: Cannot assign to class variable "x" via instance print(a.x) # OK -- can be read through an instance .. note:: If you need to support Python 3 versions 3.5.2 or earlier, you have to import ``ClassVar`` from ``typing_extensions`` instead (available on PyPI). If you use Python 2.7, you can import it from ``typing``. It's not necessary to annotate all class variables using ``ClassVar``. An attribute without the ``ClassVar`` annotation can still be used as a class variable. However, mypy won't prevent it from being used as an instance variable, as discussed previously: .. code-block:: python class A: x = 0 # Can be used as a class or instance variable A.x += 1 # OK a = A() a.x = 1 # Also OK Note that ``ClassVar`` is not a class, and you can't use it with ``isinstance()`` or ``issubclass()``. It does not change Python runtime behavior -- it's only for type checkers such as mypy (and also helpful for human readers). You can also omit the square brackets and the variable type in a ``ClassVar`` annotation, but this might not do what you'd expect: .. code-block:: python class A: y: ClassVar = 0 # Type implicitly Any! In this case the type of the attribute will be implicitly ``Any``. This behavior will change in the future, since it's surprising. .. note:: A ``ClassVar`` type parameter cannot include type variables: ``ClassVar[T]`` and ``ClassVar[List[T]]`` are both invalid if ``T`` is a type variable (see :ref:`generic-classes` for more about type variables). Overriding statically typed methods *********************************** Loading @@ -85,27 +178,35 @@ override has a compatible signature: .. code-block:: python class A: class Base: def f(self, x: int) -> None: ... class B(A): class Derived1(Base): def f(self, x: str) -> None: # Error: type of 'x' incompatible ... class C(A): class Derived2(Base): def f(self, x: int, y: int) -> None: # Error: too many arguments ... class D(A): class Derived3(Base): def f(self, x: int) -> None: # OK ... class Derived4(Base): def f(self, x: float) -> None: # OK: mypy treats int as a subtype of float ... class Derived5(Base): def f(self, x: int, y: int = 0) -> None: # OK: accepts more than the base ... # class method .. note:: You can also vary return types **covariantly** in overriding. For example, you could override the return type ``object`` with a subtype such as ``int``. Similarly, you can vary argument types example, you could override the return type ``Iterable[int]`` with a subtype such as ``List[int]``. Similarly, you can vary argument types **contravariantly** -- subclasses can have more general argument types. You can also override a statically typed method with a dynamically Loading @@ -120,50 +221,103 @@ effect at runtime: .. code-block:: python class A: class Base: def inc(self, x: int) -> int: return x + 1 class B(A): class Derived(Base): def inc(self, x): # Override, dynamically typed return 'hello' # Incompatible with 'A', but no mypy error return 'hello' # Incompatible with 'Base', but no mypy error Abstract base classes and multiple inheritance ********************************************** Mypy supports Python abstract base classes (ABCs). Abstract classes have at least one abstract method or property that must be implemented by a subclass. You can define abstract base classes using the ``abc.ABCMeta`` metaclass, and the ``abc.abstractmethod`` and ``abc.abstractproperty`` function decorators. Example: by any *concrete* (non-abstract) subclass. You can define abstract base classes using the ``abc.ABCMeta`` metaclass and the ``abc.abstractmethod`` function decorator. Example: .. code-block:: python from abc import ABCMeta, abstractmethod class A(metaclass=ABCMeta): class Animal(metaclass=ABCMeta): @abstractmethod def foo(self, x: int) -> None: pass def eat(self, food: str) -> None: pass @property @abstractmethod def bar(self) -> str: pass def can_walk(self) -> bool: pass class Cat(Animal): def eat(self, food: str) -> None: ... # Body omitted class B(A): def foo(self, x: int) -> None: ... def bar(self) -> str: return 'x' @property def can_walk(self) -> bool: return True a = A() # Error: 'A' is abstract b = B() # OK x = Animal() # Error: 'Animal' is abstract due to 'eat' and 'can_walk' y = Cat() # OK .. note:: In Python 2.7 you have to use ``@abc.abstractproperty`` to define an abstract property. Note that mypy performs checking for unimplemented abstract methods even if you omit the ``ABCMeta`` metaclass. This can be useful if the metaclass would cause runtime metaclass conflicts. Since you can't create instances of ABCs, they are most commonly used in type annotations. For example, this method accepts arbitrary iterables containing arbitrary animals (instances of concrete ``Animal`` subclasses): .. code-block:: python def feed_all(animals: Iterable[Animal], food: str) -> None: for animal in animals: animal.eat(food) There is one important peculiarity about how ABCs work in Python -- whether a particular class is abstract or not is somewhat implicit. In the example below, ``Derived`` is treated as an abstract base class since ``Derived`` inherits an abstract ``f`` method from ``Base`` and doesn't explicitly implement it. The definition of ``Derived`` generates no errors from mypy, since it's a valid ABC: .. code-block:: python from abc import ABCMeta, abstractmethod class Base(metaclass=ABCMeta): @abstractmethod def f(self, x: int) -> None: pass class Derived(Base): # No error -- Derived is implicitly abstract def g(self) -> None: ... Attempting to create an instance of ``Derived`` will be rejected, however: .. code-block:: python d = Derived() # Error: 'Derived' is abstract .. note:: It's a common error to forget to implement an abstract method. As shown above, the class definition will not generate an error in this case, but any attempt to construct an instance will be flagged as an error. A class can inherit any number of classes, both abstract and concrete. As with normal overrides, a dynamically typed method can implement a statically typed method defined in any base class, including an abstract method defined in an abstract base class. override or implement a statically typed method defined in any base class, including an abstract method defined in an abstract base class. You can implement an abstract property using either a normal property or an instance variable.
docs/source/common_issues.rst +52 −0 Original line number Diff line number Diff line Loading @@ -382,6 +382,23 @@ More specifically, mypy will understand the use of ``sys.version_info`` and else: # Other systems As a special case, you can also use one of these checks in a top-level (unindented) ``assert``; this makes mypy skip the rest of the file. Example: .. code-block:: python import sys assert sys.platform != 'win32' # The rest of this file doesn't apply to Windows. Some other expressions exhibit similar behavior; in particular, ``typing.TYPE_CHECKING``, variables named ``MYPY``, and any variable whose name is passed to ``--always-true`` or ``--always-false``. (However, ``True`` and ``False`` are not treated specially!) .. note:: Mypy currently does not support more complex checks, and does not assign Loading Loading @@ -496,6 +513,41 @@ Here's the above example modified to use ``MYPY``: return [arg] Using classes that are generic in stubs but not at runtime ---------------------------------------------------------- Some classes are declared as generic in stubs, but not at runtime. Examples in the standard library include ``os.PathLike`` and ``queue.Queue``. Subscripting such a class will result in a runtime error: .. code-block:: python from queue import Queue class Tasks(Queue[str]): # TypeError: 'type' object is not subscriptable ... results: Queue[int] = Queue() # TypeError: 'type' object is not subscriptable To avoid these errors while still having precise types you can either use string literal types or ``typing.TYPE_CHECKING``: .. code-block:: python from queue import Queue from typing import TYPE_CHECKING if TYPE_CHECKING: BaseQueue = Queue[str] # this is only processed by mypy else: BaseQueue = Queue # this is not seen by mypy but will be executed at runtime. class Tasks(BaseQueue): # OK ... results: 'Queue[int]' = Queue() # OK .. _silencing-linters: Silencing linters Loading