Syntax for variable annotations (PEP 526)
Python 3.6 introduced a new syntax for variable annotations (inglobal, class and local scopes). There are two variants of thesyntax, with or without an initializer expression:
- from typing import Optional
- foo: Optional[int] # No initializer
- bar: List[str] = [] # Initializer
You can also mark names intended to be used as class variables withClassVar
. In a pinch you can also use ClassVar
in # type
comments. Example:
- from typing import ClassVar
- class C:
- x: int # Instance variable
- y: ClassVar[int] # Class variable
- z = None # type: ClassVar[int]
- def foo(self) -> None:
- self.x = 0 # OK
- self.y = 0 # Error: Cannot assign to class variable "y" via instance
- C.y = 0 # This is OK