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:

  1. from typing import Optional
  2. foo: Optional[int] # No initializer
  3. 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 # typecomments. Example:

  1. from typing import ClassVar
  2.  
  3. class C:
  4. x: int # Instance variable
  5. y: ClassVar[int] # Class variable
  6. z = None # type: ClassVar[int]
  7.  
  8. def foo(self) -> None:
  9. self.x = 0 # OK
  10. self.y = 0 # Error: Cannot assign to class variable "y" via instance
  11.  
  12. C.y = 0 # This is OK