|
| 1 | +# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#instantiating-generic-classes-and-type-erasure |
| 2 | + |
| 3 | +from typing import Any, TypeVar, Generic, assert_type |
| 4 | + |
| 5 | +T = TypeVar("T") |
| 6 | + |
| 7 | +# > If the constructor (__init__ or __new__) uses T in its signature, and a |
| 8 | +# > corresponding argument value is passed, the type of the corresponding |
| 9 | +# > argument(s) is substituted. Otherwise, Any is assumed. |
| 10 | + |
| 11 | +class Node(Generic[T]): |
| 12 | + label: T |
| 13 | + def __init__(self, label: T | None = None) -> None: ... |
| 14 | + |
| 15 | +assert_type(Node(''), Node[str]) |
| 16 | +assert_type(Node(0), Node[int]) |
| 17 | +assert_type(Node(), Node[Any]) |
| 18 | + |
| 19 | +assert_type(Node(0).label, int) |
| 20 | +assert_type(Node().label, Any) |
| 21 | + |
| 22 | +# > In case the inferred type uses [Any] but the intended type is more specific, |
| 23 | +# > you can use an annotation to force the type of the variable, e.g.: |
| 24 | + |
| 25 | +n1: Node[int] = Node() |
| 26 | +assert_type(n1, Node[int]) |
| 27 | +n2: Node[str] = Node() |
| 28 | +assert_type(n2, Node[str]) |
| 29 | + |
| 30 | +n3 = Node[int]() |
| 31 | +assert_type(n3, Node[int]) |
| 32 | +n4 = Node[str]() |
| 33 | +assert_type(n4, Node[str]) |
| 34 | + |
| 35 | +n5 = Node[int](0) # OK |
| 36 | +n6 = Node[int]("") # Type error |
| 37 | +n7 = Node[str]("") # OK |
| 38 | +n8 = Node[str](0) # Type error |
| 39 | + |
| 40 | +Node[int].label = 1 # Type error |
| 41 | +Node[int].label # Type error |
| 42 | +Node.label = 1 # Type error |
| 43 | +Node.label # Type error |
| 44 | +type(n1).label # Type error |
| 45 | +assert_type(n1.label, int) |
| 46 | +assert_type(Node[int]().label, int) |
| 47 | +n1.label = 1 # OK |
| 48 | + |
| 49 | +# > [...] generic versions of concrete collections can be instantiated: |
| 50 | + |
| 51 | +from typing import DefaultDict |
| 52 | + |
| 53 | +data = DefaultDict[int, bytes]() |
| 54 | +assert_type(data[0], bytes) |
0 commit comments