@@ -6,6 +6,13 @@ code. These types are interesting in that they are parametrised by other types!
66A ``list[str] `` isn't just a list, it's a list of strings. Types with type
77parameters like this are called *generic types *.
88
9+ .. note ::
10+
11+ Python 3.12 introduced :pep: `695 `, which allows defining generics using
12+ type parameter syntax (e.g., ``class Foo[T]: `` and ``def func[T](x: T) -> T: ``).
13+ The older ``TypeVar `` and ``Generic ``-based syntax remains supported
14+ for compatibility with earlier Python versions.
15+
916You can define your own generic classes that take type parameters, similar to
1017built-in types such as ``list[X] ``. Note that such user-defined generics are a
1118moderately advanced feature and you can get far without ever using them.
@@ -19,11 +26,7 @@ Here is a very simple generic class that represents a stack:
1926
2027.. code-block :: python
2128
22- from typing import TypeVar, Generic
23-
24- T = TypeVar(' T' )
25-
26- class Stack (Generic[T]):
29+ class Stack[T]:
2730 def __init__ (self ) -> None :
2831 # Create an empty list with items of type T
2932 self .items: list[T] = []
@@ -37,6 +40,17 @@ Here is a very simple generic class that represents a stack:
3740 def empty (self ) -> bool :
3841 return not self .items
3942
43+ For compatibility with older Python versions, the same class may be written as:
44+
45+ .. code-block :: python
46+
47+ from typing import TypeVar, Generic
48+
49+ T = TypeVar(' T' )
50+
51+ class Stack (Generic[T]):
52+ ...
53+
4054 The ``Stack `` class can be used to represent a stack of any type:
4155``Stack[int] ``, ``Stack[tuple[int, str]] ``, etc.
4256
@@ -56,7 +70,7 @@ construction of the instance will be type checked correspondingly.
5670
5771.. code-block :: python
5872
59- class Box (Generic [T]) :
73+ class Box[T]:
6074 def __init__ (self , content : T) -> None :
6175 self .content = content
6276
@@ -96,12 +110,12 @@ can be used as a base class for another class (generic or non-generic). For exam
96110 data: StrDict[int , int ] # error: "StrDict" expects no type arguments, but 2 given
97111 data2: StrDict # OK
98112
99- # This is a user-defined generic class
100- class Receiver (Generic[T]):
101- def accept (self , value : T) -> None : ...
113+ # This is a user-defined generic class
114+ class Receiver (Generic[T]):
115+ def accept (self , value : T) -> None : ...
102116
103- # This is a generic subclass of Receiver
104- class AdvancedReceiver (Receiver[T]): ...
117+ # This is a generic subclass of Receiver
118+ class AdvancedReceiver (Receiver[T]): ...
105119
106120 .. note ::
107121
0 commit comments