@@ -7,3 +7,78 @@ including the following:
7
7
- inheritance between generic classes
8
8
- compatibility and subtyping of generic types, including covariance of generic types
9
9
- ``super() ``
10
+
11
+
12
+ .. _attrs_package :
13
+
14
+ The attrs package
15
+ *****************
16
+
17
+ `attrs <https://www.attrs.org/en/stable >`_ is a package that lets you define
18
+ classes without writing boilerplate code. Mypy can detect uses of the
19
+ package and will generate the necessary method definitions for decorated
20
+ classes using the type annotations it finds.
21
+ Type annotations can be added as follows:
22
+
23
+ .. code-block :: python
24
+
25
+ import attr
26
+ @attr.s
27
+ class A :
28
+ one: int = attr.ib() # Variable annotation (Python 3.6+)
29
+ two = attr.ib() # type: int # Type comment
30
+ three = attr.ib(type = int ) # type= argument
31
+
32
+ If you're using ``auto_attribs=True `` you must use variable annotations.
33
+
34
+ .. code-block :: python
35
+
36
+ import attr
37
+ @attr.s (auto_attribs = True )
38
+ class A :
39
+ one: int
40
+ two: int = 7
41
+ three: int = attr.ib(8 )
42
+
43
+ Typeshed has a couple of "white lie" annotations to make type checking
44
+ easier. ``attr.ib `` and ``attr.Factory `` actually return objects, but the
45
+ annotation says these return the types that they expect to be assigned to.
46
+ That enables this to work:
47
+
48
+ .. code-block :: python
49
+
50
+ import attr
51
+ from typing import Dict
52
+ @attr.s (auto_attribs = True )
53
+ one: int = attr.ib(8 )
54
+ two: Dict[str , str ] = attr.Factory(dict )
55
+ bad: str = attr.ib(16 ) # Error: can't assign int to str
56
+
57
+ Caveats/Known Issues
58
+ ====================
59
+
60
+ * The detection of attr classes and attributes works by function name only.
61
+ This means that if you have your own helper functions that, for example,
62
+ ``return attr.ib() `` mypy will not see them.
63
+
64
+ * All boolean arguments that mypy cares about must be literal ``True `` or ``False ``.
65
+ e.g the following will not work:
66
+
67
+ .. code-block :: python
68
+
69
+ import attr
70
+ YES = True
71
+ @attr.s (init = YES )
72
+ class A :
73
+ ...
74
+
75
+ * Currently, ``converter `` only supports named functions. If mypy finds something else it
76
+ will complain about not understanding the argument and the type annotation in
77
+ ``__init__ `` will be replaced by ``Any ``.
78
+
79
+ * `Validator decorators <http://www.attrs.org/en/stable/examples.html#decorator >`_
80
+ and `default decorators <http://www.attrs.org/en/stable/examples.html#defaults >`_
81
+ are not type-checked against the attribute they are setting/validating.
82
+
83
+ * Method definitions added by mypy currently overwrite any existing method
84
+ definitions.
0 commit comments