Skip to content

Commit 2afd663

Browse files
geoffthynek
andauthored
Document how to handle class variables/constants in typed syntax (#1352)
* Document how to handle class variables/constants in typed syntax This is mentioned very briefly in the API docs for `auto_attrib` but it's not easy to find if you don't already know about `typing.ClassVar`. * Fix typo * 2 empty lines before headers --------- Co-authored-by: Hynek Schlawack <[email protected]>
1 parent a785e6b commit 2afd663

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

docs/types.md

+18
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,24 @@ Your constructive feedback is welcome in both [attrs#795](https://github.com/pyt
106106
Generally speaking, the decision on improving *attrs* support in Pyright is entirely Microsoft's prerogative and they unequivocally indicated that they'll only add support for features that go through the PEP process, though.
107107
:::
108108

109+
110+
## Class variables and constants
111+
112+
If you are adding type annotations to all of your code, you might wonder how to define a class variable (as opposed to an instance variable), because a value assigned at class scope becomes a default for that attribute.
113+
The proper way to type such a class variable, though, is with {data}`typing.ClassVar`, which indicates that the variable should only be assigned in the class (or its subclasses) and not in instances of the class.
114+
*attrs* will skip over members annotated with {data}`typing.ClassVar`, allowing you to write a type annotation without turning the member into an attribute.
115+
Class variables are often used for constants, though they can also be used for mutable singleton data shared across all instances of the class.
116+
117+
```
118+
@attrs.define
119+
class PngHeader:
120+
SIGNATURE: typing.ClassVar[bytes] = b'\x89PNG\r\n\x1a\n'
121+
height: int
122+
width: int
123+
interlaced: int = 0
124+
...
125+
```
126+
109127
[Mypy]: http://mypy-lang.org
110128
[Pyright]: https://github.com/microsoft/pyright
111129
[*pytype*]: https://google.github.io/pytype/

0 commit comments

Comments
 (0)