|
| 1 | +Type Annotations |
| 2 | +================ |
| 3 | + |
| 4 | +``attrs`` comes with first class support for type annotations for both Python 3.6 (:pep:`526`) and legacy syntax. |
| 5 | + |
| 6 | +On Python 3.6 and later, you can even drop the :func:`attr.ib`\ s if you're willing to annotate *all* attributes. |
| 7 | +That means that on modern Python versions, the declaration part of the example from the README can be simplified to: |
| 8 | + |
| 9 | + |
| 10 | +.. doctest:: |
| 11 | + |
| 12 | + >>> import attr |
| 13 | + >>> import typing |
| 14 | + |
| 15 | + >>> @attr.s(auto_attribs=True) |
| 16 | + ... class SomeClass: |
| 17 | + ... a_number: int = 42 |
| 18 | + ... list_of_numbers: typing.List[int] = attr.Factory(list) |
| 19 | + |
| 20 | + >>> sc = SomeClass(1, [1, 2, 3]) |
| 21 | + >>> sc |
| 22 | + SomeClass(a_number=1, list_of_numbers=[1, 2, 3]) |
| 23 | + >>> attr.fields(SomeClass).a_number.type |
| 24 | + <class 'int'> |
| 25 | + |
| 26 | +You can still use :func:`attr.ib` for advanced features, but you don't have to. |
| 27 | + |
| 28 | +Please note that these types are *only metadata* that can be queried from the class and they aren't used for anything out of the box! |
| 29 | + |
| 30 | + |
| 31 | +mypy |
| 32 | +---- |
| 33 | + |
| 34 | +While having a nice syntax for type metadata is great, it's even greater that `mypy <http://mypy-lang.org>`_ as of 0.570 ships with a dedicated ``attrs`` plugin which allows you to statically check your code. |
| 35 | + |
| 36 | +Imagine you add another line that tries to instantiate the defined class using ``SomeClass("23")``. |
| 37 | +Mypy will catch that error for you: |
| 38 | + |
| 39 | +.. code-block:: console |
| 40 | +
|
| 41 | + $ mypy t.py |
| 42 | + t.py:12: error: Argument 1 to "SomeClass" has incompatible type "str"; expected "int" |
| 43 | +
|
| 44 | +This happens *without* running your code! |
| 45 | + |
| 46 | +And it also works with *both* Python 2-style annotation styles. |
| 47 | +To mypy, this code is equivalent to the one above: |
| 48 | + |
| 49 | +.. code-block:: python |
| 50 | +
|
| 51 | + @attr.s |
| 52 | + class SomeClass(object): |
| 53 | + a_number = attr.ib(default=42) # type: int |
| 54 | + list_of_numbers = attr.ib(factory=list, type=typing.List[int]) |
| 55 | +
|
| 56 | +***** |
| 57 | + |
| 58 | +The addition of static types is certainly one of the most exciting features in the Python ecosystem and helps you writing *correct* and *verified self-documenting* code. |
| 59 | + |
| 60 | +If you don't know where to start, Carl Meyer gave a great talk on `Type-checked Python in the Real World <https://www.youtube.com/watch?v=pMgmKJyWKn8>`_ at PyCon US 2018 that will help you to get started in no time. |
0 commit comments