diff --git a/pep-0526.txt b/pep-0526.txt index 84d4f5d93d8..ba31b53b560 100644 --- a/pep-0526.txt +++ b/pep-0526.txt @@ -142,7 +142,7 @@ it a local:: def f(): a: int print(a) # raises UnboundLocalError - # Commenting out the ``a: int`` makes it a NameError! + # Commenting out the ``a: int`` makes it a NameError. as if the code were:: @@ -150,7 +150,7 @@ as if the code were:: if False: a = 0 print(a) # raises UnboundLocalError -Any duplicate type annotations will be ignored. Although static type +Any duplicate type annotations will be ignored. However, static type checkers will issue a warning for annotations of the same variable by a different type:: @@ -222,6 +222,23 @@ As a matter of convenience, instance attributes can be annotated in def __init__(self, content): self.content: T = content +Annotating expressions +********************** + +If the initial value is specified, then the target of the annotation can be +any valid assignment target:: + + class Cls: + pass + + c = Cls + c.x: int = 0 # Annotates ``c.x`` with ``int``.. + c.y: int # Invalid syntax: no initial value was specified! + + d = {} + d['a']: int = 0 # Annotates ``d['a']`` with ``int``. + d['b']: int # Invalid again. + Where annotations aren't allowed ******************************** @@ -270,10 +287,26 @@ Changes to standard library and documentation Runtime effects of type annotations =================================== -Variable annotations that are found at a module or class level are -evaluated and stored in ``__annotations__`` attribute of that module or -class as a dictionary mapping from names to evaluated annotations. -Here is an example:: +As stated under "Variable Annotations", annotating a local variable will cause +the interpreter to treat it as a local, even if it was never assigned to. + +If a variable annotation is for a local variable, the annotation will not be +evaluated:: + + def f(): + x: NonexistentName # No error. + +However, if it is at a module or class level, then the type *will* be +evaluated:: + + x: NonexistentName # Error! + class X: + attr: NonexistentName # Error! + +In addition, at the module, or class level, if the item being annotated is a +simple name, then it and the annotation will be stored in the +``__annotations__`` attribute of that module or class as a dictionary mapping +from names to evaluated annotations. Here is an example:: from typing import Dict class Player: