Skip to content

Commit 510b267

Browse files
committed
Clarify generic class attribute access
See python/mypy#2878
1 parent 7ca8985 commit 510b267

1 file changed

Lines changed: 17 additions & 1 deletion

File tree

‎pep-0484.txt‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -583,6 +583,7 @@ argument(s) is substituted. Otherwise, ``Any`` is assumed. Example::
583583
class Node(Generic[T]):
584584
def __init__(self, label: T = None) -> None:
585585
...
586+
x: None # Type: T
586587

587588
x = Node('') # Inferred type is Node[str]
588589
y = Node(0) # Inferred type is Node[int]
@@ -610,6 +611,21 @@ the runtime class of the objects created by instantiating them doesn't
610611
record the distinction. This behavior is called "type erasure"; it is
611612
common practice in languages with generics (e.g. Java, TypeScript).
612613

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::
617+
618+
# (continued from previous example)
619+
Node[int].x = 1 # Error
620+
Node[int].x # Error
621+
Node.x = 1 # Error
622+
Node.x # Error
623+
type(p).x # Error
624+
p.x # Ok
625+
Node[int]().x # Ok
626+
627+
In addition, ``ClassVar`` cannot be parametrized.
628+
613629
Generic versions of abstract collections like ``Mapping`` or ``Sequence``
614630
and generic versions of built-in classes -- ``List``, ``Dict``, ``Set``,
615631
and ``FrozenSet`` -- cannot be instantiated. However, concrete user-defined
@@ -2439,7 +2455,7 @@ Copyright
24392455
This document has been placed in the public domain.
24402456

24412457

2442-
2458+
24432459
..
24442460
Local Variables:
24452461
mode: indented-text

0 commit comments

Comments
 (0)