Skip to content

Commit

Permalink
Add information on valid annotations targets and clarify runtime effects
Browse files Browse the repository at this point in the history
  • Loading branch information
refi64 committed Aug 29, 2016
1 parent a74dd41 commit e651357
Showing 1 changed file with 39 additions and 6 deletions.
45 changes: 39 additions & 6 deletions pep-0526.txt
Original file line number Diff line number Diff line change
Expand Up @@ -142,15 +142,15 @@ 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::

def f():
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::

Expand Down Expand Up @@ -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
********************************

Expand Down Expand Up @@ -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:
Expand Down

0 comments on commit e651357

Please sign in to comment.