@@ -288,7 +288,7 @@ elements. Example::
288
288
289
289
def notify_by_email(employees: Set[Employee], overrides: Mapping[str, str]) -> None: ...
290
290
291
- Generics can be parametrized by using a new factory available in
291
+ Generics can be parameterized by using a new factory available in
292
292
``typing`` called ``TypeVar``. Example::
293
293
294
294
from typing import Sequence, TypeVar
@@ -583,7 +583,7 @@ argument(s) is substituted. Otherwise, ``Any`` is assumed. Example::
583
583
class Node(Generic[T]):
584
584
def __init__(self, label: T = None) -> None:
585
585
...
586
- x: None # Type: T
586
+ x = None # Type: T
587
587
588
588
x = Node('') # Inferred type is Node[str]
589
589
y = Node(0) # Inferred type is Node[int]
@@ -611,20 +611,23 @@ the runtime class of the objects created by instantiating them doesn't
611
611
record the distinction. This behavior is called "type erasure"; it is
612
612
common practice in languages with generics (e.g. Java, TypeScript).
613
613
614
- Class attribute of a generic class can be looked up only through the instance
615
- of the class; any attempt to use generic classes (parametrized or not) to
616
- access attributes will result in both type check failure and runtime error::
614
+ Using generic classes (parameterized or not) to access attributes will result
615
+ in both type check failure and runtime error. Outside the class definition
616
+ body, a class attribute cannot be assigned, and can only be looked up by
617
+ accessing it through the class instance that does not have same-named
618
+ instance attribute::
617
619
618
620
# (continued from previous example)
619
621
Node[int].x = 1 # Error
620
622
Node[int].x # Error
621
623
Node.x = 1 # Error
622
624
Node.x # Error
623
625
type(p).x # Error
624
- p.x # Ok
625
- Node[int]().x # Ok
626
+ p.x # Ok (evaluates to None)
627
+ Node[int]().x # Ok (evaluates to None)
628
+ p.x = 1 # Will assign to instance attribute
626
629
627
- In addition, ``ClassVar`` cannot be parametrized .
630
+ In addition, ``ClassVar`` cannot be parameterized .
628
631
629
632
Generic versions of abstract collections like ``Mapping`` or ``Sequence``
630
633
and generic versions of built-in classes -- ``List``, ``Dict``, ``Set``,
0 commit comments