Skip to content

Commit 03d609c

Browse files
NickCrewstushar-deepsource
authored andcommitted
Use list[int] instead of typing.List[int] in generics.rst (python#11377)
Also change typing.Tuple to tuple, typing.Dict to dict, etc.
1 parent 1344a28 commit 03d609c

File tree

1 file changed

+25
-22
lines changed

1 file changed

+25
-22
lines changed

docs/source/generics.rst

Lines changed: 25 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ Generics
22
========
33

44
This section explains how you can define your own generic classes that take
5-
one or more type parameters, similar to built-in types such as ``List[X]``.
5+
one or more type parameters, similar to built-in types such as ``list[X]``.
66
User-defined generics are a moderately advanced feature and you can get far
77
without ever using them -- feel free to skip this section and come back later.
88

@@ -13,8 +13,8 @@ Defining generic classes
1313

1414
The built-in collection classes are generic classes. Generic types
1515
have one or more type parameters, which can be arbitrary types. For
16-
example, ``Dict[int, str]`` has the type parameters ``int`` and
17-
``str``, and ``List[int]`` has a type parameter ``int``.
16+
example, ``dict[int, str]`` has the type parameters ``int`` and
17+
``str``, and ``list[int]`` has a type parameter ``int``.
1818

1919
Programs can also define new generic classes. Here is a very simple
2020
generic class that represents a stack:
@@ -28,7 +28,7 @@ generic class that represents a stack:
2828
class Stack(Generic[T]):
2929
def __init__(self) -> None:
3030
# Create an empty list with items of type T
31-
self.items: List[T] = []
31+
self.items: list[T] = []
3232
3333
def push(self, item: T) -> None:
3434
self.items.append(item)
@@ -40,7 +40,7 @@ generic class that represents a stack:
4040
return not self.items
4141
4242
The ``Stack`` class can be used to represent a stack of any type:
43-
``Stack[int]``, ``Stack[Tuple[int, str]]``, etc.
43+
``Stack[int]``, ``Stack[tuple[int, str]]``, etc.
4444

4545
Using ``Stack`` is similar to built-in container types:
4646

@@ -90,13 +90,16 @@ instantiation:
9090
>>> print(Stack[int]().__class__)
9191
__main__.Stack
9292
93-
Note that built-in types :py:class:`list`, :py:class:`dict` and so on do not support
94-
indexing in Python. This is why we have the aliases :py:class:`~typing.List`, :py:class:`~typing.Dict`
93+
For Python 3.8 and lower, note that built-in types :py:class:`list`,
94+
:py:class:`dict` and so on do not support indexing in Python.
95+
This is why we have the aliases :py:class:`~typing.List`, :py:class:`~typing.Dict`
9596
and so on in the :py:mod:`typing` module. Indexing these aliases gives
9697
you a class that directly inherits from the target class in Python:
9798

9899
.. code-block:: python
99100
101+
>>> # Only relevant for Python 3.8 and below
102+
>>> # For Python 3.9 onwards, prefer `list[int]` syntax
100103
>>> from typing import List
101104
>>> List[int]
102105
typing.List[int]
@@ -121,7 +124,7 @@ non-generic. For example:
121124

122125
.. code-block:: python
123126
124-
from typing import Generic, TypeVar, Mapping, Iterator, Dict
127+
from typing import Generic, TypeVar, Mapping, Iterator
125128
126129
KT = TypeVar('KT')
127130
VT = TypeVar('VT')
@@ -136,7 +139,7 @@ non-generic. For example:
136139
137140
items: MyMap[str, int] # Okay
138141
139-
class StrDict(Dict[str, str]): # This is a non-generic subclass of Dict
142+
class StrDict(dict[str, str]): # This is a non-generic subclass of dict
140143
def __str__(self) -> str:
141144
return 'StrDict({})'.format(super().__str__())
142145
@@ -284,15 +287,15 @@ For class methods, you can also define generic ``cls``, using :py:class:`Type[T]
284287

285288
.. code-block:: python
286289
287-
from typing import TypeVar, Tuple, Type
290+
from typing import TypeVar, Type
288291
289292
T = TypeVar('T', bound='Friend')
290293
291294
class Friend:
292295
other = None # type: Friend
293296
294297
@classmethod
295-
def make_pair(cls: Type[T]) -> Tuple[T, T]:
298+
def make_pair(cls: Type[T]) -> tuple[T, T]:
296299
a, b = cls(), cls()
297300
a.other = b
298301
b.other = a
@@ -345,8 +348,8 @@ Let us illustrate this by few simple examples:
345348

346349
.. code-block:: python
347350
348-
def salaries(staff: List[Manager],
349-
accountant: Callable[[Manager], int]) -> List[int]: ...
351+
def salaries(staff: list[Manager],
352+
accountant: Callable[[Manager], int]) -> list[int]: ...
350353
351354
This function needs a callable that can calculate a salary for managers, and
352355
if we give it a callable that can calculate a salary for an arbitrary
@@ -363,10 +366,10 @@ Let us illustrate this by few simple examples:
363366
def rotate(self):
364367
...
365368
366-
def add_one(things: List[Shape]) -> None:
369+
def add_one(things: list[Shape]) -> None:
367370
things.append(Shape())
368371
369-
my_things: List[Circle] = []
372+
my_things: list[Circle] = []
370373
add_one(my_things) # This may appear safe, but...
371374
my_things[0].rotate() # ...this will fail
372375
@@ -532,7 +535,7 @@ Here's a complete example of a function decorator:
532535

533536
.. code-block:: python
534537
535-
from typing import Any, Callable, TypeVar, Tuple, cast
538+
from typing import Any, Callable, TypeVar, cast
536539
537540
F = TypeVar('F', bound=Callable[..., Any])
538541
@@ -724,32 +727,32 @@ variables replaced with ``Any``. Examples (following :pep:`PEP 484: Type aliases
724727

725728
.. code-block:: python
726729
727-
from typing import TypeVar, Iterable, Tuple, Union, Callable
730+
from typing import TypeVar, Iterable, Union, Callable
728731
729732
S = TypeVar('S')
730733
731-
TInt = Tuple[int, S]
734+
TInt = tuple[int, S]
732735
UInt = Union[S, int]
733736
CBack = Callable[..., S]
734737
735738
def response(query: str) -> UInt[str]: # Same as Union[str, int]
736739
...
737740
def activate(cb: CBack[S]) -> S: # Same as Callable[..., S]
738741
...
739-
table_entry: TInt # Same as Tuple[int, Any]
742+
table_entry: TInt # Same as tuple[int, Any]
740743
741744
T = TypeVar('T', int, float, complex)
742745
743-
Vec = Iterable[Tuple[T, T]]
746+
Vec = Iterable[tuple[T, T]]
744747
745748
def inproduct(v: Vec[T]) -> T:
746749
return sum(x*y for x, y in v)
747750
748751
def dilate(v: Vec[T], scale: T) -> Vec[T]:
749752
return ((x * scale, y * scale) for x, y in v)
750753
751-
v1: Vec[int] = [] # Same as Iterable[Tuple[int, int]]
752-
v2: Vec = [] # Same as Iterable[Tuple[Any, Any]]
754+
v1: Vec[int] = [] # Same as Iterable[tuple[int, int]]
755+
v2: Vec = [] # Same as Iterable[tuple[Any, Any]]
753756
v3: Vec[int, int] = [] # Error: Invalid alias, too many type arguments!
754757
755758
Type aliases can be imported from modules just like other names. An

0 commit comments

Comments
 (0)