Skip to content

Commit 4669929

Browse files
authored
Replace List[X] with list[X] in docs (#11450)
1 parent f194551 commit 4669929

18 files changed

+178
-188
lines changed

docs/source/additional_features.rst

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,10 +21,10 @@ They can be defined using the :py:func:`@dataclasses.dataclass
2121
@dataclass
2222
class Application:
2323
name: str
24-
plugins: List[str] = field(default_factory=list)
24+
plugins: list[str] = field(default_factory=list)
2525
2626
test = Application("Testing...") # OK
27-
bad = Application("Testing...", "with plugin") # Error: List[str] expected
27+
bad = Application("Testing...", "with plugin") # Error: list[str] expected
2828
2929
Mypy will detect special methods (such as :py:meth:`__lt__ <object.__lt__>`) depending on the flags used to
3030
define dataclasses. For example:

docs/source/cheat_sheet_py3.rst

Lines changed: 20 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ Built-in types
4545

4646
.. code-block:: python
4747
48+
4849
from typing import List, Set, Dict, Tuple, Optional
4950
5051
# For simple built-in types, just use the name of the type
@@ -60,16 +61,16 @@ Built-in types
6061
x: set[int] = {6, 7}
6162
6263
# In Python 3.8 and earlier, the name of the collection type is
63-
# capitalized, and the type is imported from 'typing'
64+
# capitalized, and the type is imported from the 'typing' module
6465
x: List[int] = [1]
6566
x: Set[int] = {6, 7}
6667
6768
# Same as above, but with type comment syntax (Python 3.5 and earlier)
6869
x = [1] # type: List[int]
6970
7071
# For mappings, we need the types of both keys and values
71-
x: dict[str, float] = {'field': 2.0} # Python 3.9+
72-
x: Dict[str, float] = {'field': 2.0}
72+
x: dict[str, float] = {"field": 2.0} # Python 3.9+
73+
x: Dict[str, float] = {"field": 2.0}
7374
7475
# For tuples of fixed size, we specify the types of all the elements
7576
x: tuple[int, str, float] = (3, "yes", 7.5) # Python 3.9+
@@ -95,7 +96,7 @@ Python 3 supports an annotation syntax for function declarations.
9596

9697
.. code-block:: python
9798
98-
from typing import Callable, Iterator, Union, Optional, List
99+
from typing import Callable, Iterator, Union, Optional
99100
100101
# This is how you annotate a function definition
101102
def stringify(num: int) -> str:
@@ -121,12 +122,12 @@ Python 3 supports an annotation syntax for function declarations.
121122
i += 1
122123
123124
# You can of course split a function annotation over multiple lines
124-
def send_email(address: Union[str, List[str]],
125+
def send_email(address: Union[str, list[str]],
125126
sender: str,
126-
cc: Optional[List[str]],
127-
bcc: Optional[List[str]],
127+
cc: Optional[list[str]],
128+
bcc: Optional[list[str]],
128129
subject='',
129-
body: Optional[List[str]] = None
130+
body: Optional[list[str]] = None
130131
) -> bool:
131132
...
132133
@@ -143,23 +144,23 @@ When you're puzzled or when things are complicated
143144

144145
.. code-block:: python
145146
146-
from typing import Union, Any, List, Optional, cast
147+
from typing import Union, Any, Optional, cast
147148
148149
# To find out what type mypy infers for an expression anywhere in
149150
# your program, wrap it in reveal_type(). Mypy will print an error
150151
# message with the type; remove it again before running the code.
151152
reveal_type(1) # -> Revealed type is "builtins.int"
152153
153154
# Use Union when something could be one of a few types
154-
x: List[Union[int, str]] = [3, 5, "test", "fun"]
155+
x: list[Union[int, str]] = [3, 5, "test", "fun"]
155156
156157
# Use Any if you don't know the type of something or it's too
157158
# dynamic to write a type for
158159
x: Any = mystery_function()
159160
160161
# If you initialize a variable with an empty container or "None"
161162
# you may have to help mypy a bit by providing a type annotation
162-
x: List[str] = []
163+
x: list[str] = []
163164
x: Optional[str] = None
164165
165166
# This makes each positional arg and each keyword arg a "str"
@@ -176,8 +177,8 @@ When you're puzzled or when things are complicated
176177
# "cast" is a helper function that lets you override the inferred
177178
# type of an expression. It's only for mypy -- there's no runtime check.
178179
a = [4]
179-
b = cast(List[int], a) # Passes fine
180-
c = cast(List[str], a) # Passes fine (no runtime check)
180+
b = cast(list[int], a) # Passes fine
181+
c = cast(list[str], a) # Passes fine (no runtime check)
181182
reveal_type(c) # -> Revealed type is "builtins.list[builtins.str]"
182183
print(c) # -> [4]; the object is not cast
183184
@@ -209,25 +210,25 @@ that are common in idiomatic Python are standardized.
209210

210211
.. code-block:: python
211212
212-
from typing import Mapping, MutableMapping, Sequence, Iterable, List, Set
213+
from typing import Mapping, MutableMapping, Sequence, Iterable
213214
214215
# Use Iterable for generic iterables (anything usable in "for"),
215216
# and Sequence where a sequence (supporting "len" and "__getitem__") is
216217
# required
217-
def f(ints: Iterable[int]) -> List[str]:
218+
def f(ints: Iterable[int]) -> list[str]:
218219
return [str(x) for x in ints]
219220
220221
f(range(1, 3))
221222
222223
# Mapping describes a dict-like object (with "__getitem__") that we won't
223224
# mutate, and MutableMapping one (with "__setitem__") that we might
224-
def f(my_mapping: Mapping[int, str]) -> List[int]:
225+
def f(my_mapping: Mapping[int, str]) -> list[int]:
225226
my_mapping[5] = 'maybe' # if we try this, mypy will throw an error...
226227
return list(my_mapping.keys())
227228
228229
f({3: 'yes', 4: 'no'})
229230
230-
def f(my_mapping: MutableMapping[int, str]) -> Set[str]:
231+
def f(my_mapping: MutableMapping[int, str]) -> set[str]:
231232
my_mapping[5] = 'maybe' # ...but mypy is OK with this.
232233
return set(my_mapping.values())
233234
@@ -262,12 +263,12 @@ Classes
262263
# You can use the ClassVar annotation to declare a class variable
263264
class Car:
264265
seats: ClassVar[int] = 4
265-
passengers: ClassVar[List[str]]
266+
passengers: ClassVar[list[str]]
266267
267268
# You can also declare the type of an attribute in "__init__"
268269
class Box:
269270
def __init__(self) -> None:
270-
self.items: List[str] = []
271+
self.items: list[str] = []
271272
272273
273274
Coroutines and asyncio

docs/source/class_basics.rst

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ a type annotation:
3333
.. code-block:: python
3434
3535
class A:
36-
x: List[int] # Declare attribute 'x' of type List[int]
36+
x: list[int] # Declare attribute 'x' of type list[int]
3737
3838
a = A()
3939
a.x = [1] # OK
@@ -48,7 +48,7 @@ than 3.6:
4848
.. code-block:: python
4949
5050
class A:
51-
x = None # type: List[int] # Declare attribute 'x' of type List[int]
51+
x = None # type: list[int] # Declare attribute 'x' of type list[int]
5252
5353
Note that attribute definitions in the class body that use a type comment
5454
are special: a ``None`` value is valid as the initializer, even though
@@ -62,7 +62,7 @@ in a method:
6262
6363
class A:
6464
def __init__(self) -> None:
65-
self.x: List[int] = []
65+
self.x: list[int] = []
6666
6767
def f(self) -> None:
6868
self.y: Any = 0
@@ -160,7 +160,7 @@ This behavior will change in the future, since it's surprising.
160160

161161
.. note::
162162
A :py:data:`~typing.ClassVar` type parameter cannot include type variables:
163-
``ClassVar[T]`` and ``ClassVar[List[T]]``
163+
``ClassVar[T]`` and ``ClassVar[list[T]]``
164164
are both invalid if ``T`` is a type variable (see :ref:`generic-classes`
165165
for more about type variables).
166166

@@ -200,7 +200,7 @@ override has a compatible signature:
200200

201201
You can also vary return types **covariantly** in overriding. For
202202
example, you could override the return type ``Iterable[int]`` with a
203-
subtype such as ``List[int]``. Similarly, you can vary argument types
203+
subtype such as ``list[int]``. Similarly, you can vary argument types
204204
**contravariantly** -- subclasses can have more general argument types.
205205

206206
You can also override a statically typed method with a dynamically

docs/source/command_line.rst

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -312,9 +312,8 @@ The following options are available:
312312
.. option:: --disallow-any-generics
313313

314314
This flag disallows usage of generic types that do not specify explicit
315-
type parameters. Moreover, built-in collections (such as :py:class:`list` and
316-
:py:class:`dict`) become disallowed as you should use their aliases from the :py:mod:`typing`
317-
module (such as :py:class:`List[int] <typing.List>` and :py:class:`Dict[str, str] <typing.Dict>`).
315+
type parameters. For example you can't use a bare ``x: list``, you must say
316+
``x: list[int]``.
318317

319318
.. option:: --disallow-subclassing-any
320319

@@ -521,10 +520,10 @@ of the above sections.
521520

522521
.. code-block:: python
523522
524-
def process(items: List[str]) -> None:
525-
# 'items' has type List[str]
523+
def process(items: list[str]) -> None:
524+
# 'items' has type list[str]
526525
items = [item.split() for item in items]
527-
# 'items' now has type List[List[str]]
526+
# 'items' now has type list[list[str]]
528527
...
529528
530529
.. option:: --local-partial-types
@@ -585,9 +584,9 @@ of the above sections.
585584

586585
.. code-block:: python
587586
588-
from typing import List, Text
587+
from typing import Text
589588
590-
items: List[int]
589+
items: list[int]
591590
if 'some string' in items: # Error: non-overlapping container check!
592591
...
593592

docs/source/error_code_list.rst

Lines changed: 30 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -117,15 +117,15 @@ Example:
117117

118118
.. code-block:: python
119119
120-
from typing import List, Optional
120+
from typing import Optional
121121
122-
def first(x: List[int]) -> Optional[int]:
122+
def first(x: list[int]) -> Optional[int]:
123123
return x[0] if x else 0
124124
125-
t = (5, 4)
126-
# Error: Argument 1 to "first" has incompatible type "Tuple[int, int]";
127-
# expected "List[int]" [arg-type]
128-
print(first(t))
125+
t = (5, 4)
126+
# Error: Argument 1 to "first" has incompatible type "tuple[int, int]";
127+
# expected "list[int]" [arg-type]
128+
print(first(t))
129129
130130
Check calls to overloaded functions [call-overload]
131131
---------------------------------------------------
@@ -171,26 +171,24 @@ This example incorrectly uses the function ``log`` as a type:
171171

172172
.. code-block:: python
173173
174-
from typing import List
174+
def log(x: object) -> None:
175+
print('log:', repr(x))
175176
176-
def log(x: object) -> None:
177-
print('log:', repr(x))
178-
179-
# Error: Function "t.log" is not valid as a type [valid-type]
180-
def log_all(objs: List[object], f: log) -> None:
181-
for x in objs:
182-
f(x)
177+
# Error: Function "t.log" is not valid as a type [valid-type]
178+
def log_all(objs: list[object], f: log) -> None:
179+
for x in objs:
180+
f(x)
183181
184182
You can use :py:data:`~typing.Callable` as the type for callable objects:
185183

186184
.. code-block:: python
187185
188-
from typing import List, Callable
186+
from typing import Callable
189187
190-
# OK
191-
def log_all(objs: List[object], f: Callable[[object], None]) -> None:
192-
for x in objs:
193-
f(x)
188+
# OK
189+
def log_all(objs: list[object], f: Callable[[object], None]) -> None:
190+
for x in objs:
191+
f(x)
194192
195193
Require annotation if variable type is unclear [var-annotated]
196194
--------------------------------------------------------------
@@ -206,23 +204,21 @@ Example with an error:
206204

207205
.. code-block:: python
208206
209-
class Bundle:
210-
def __init__(self) -> None:
211-
# Error: Need type annotation for "items"
212-
# (hint: "items: List[<type>] = ...") [var-annotated]
213-
self.items = []
207+
class Bundle:
208+
def __init__(self) -> None:
209+
# Error: Need type annotation for "items"
210+
# (hint: "items: list[<type>] = ...") [var-annotated]
211+
self.items = []
214212
215-
reveal_type(Bundle().items) # list[Any]
213+
reveal_type(Bundle().items) # list[Any]
216214
217215
To address this, we add an explicit annotation:
218216

219217
.. code-block:: python
220218
221-
from typing import List
222-
223-
class Bundle:
224-
def __init__(self) -> None:
225-
self.items: List[str] = [] # OK
219+
class Bundle:
220+
def __init__(self) -> None:
221+
self.items: list[str] = [] # OK
226222
227223
reveal_type(Bundle().items) # list[str]
228224
@@ -377,10 +373,10 @@ Example:
377373
378374
a['x'] # OK
379375
380-
# Error: Invalid index type "int" for "Dict[str, int]"; expected type "str" [index]
376+
# Error: Invalid index type "int" for "dict[str, int]"; expected type "str" [index]
381377
print(a[1])
382378
383-
# Error: Invalid index type "bytes" for "Dict[str, int]"; expected type "str" [index]
379+
# Error: Invalid index type "bytes" for "dict[str, int]"; expected type "str" [index]
384380
a[b'x'] = 4
385381
386382
Check list items [list-item]
@@ -394,10 +390,8 @@ Example:
394390

395391
.. code-block:: python
396392
397-
from typing import List
398-
399393
# Error: List item 0 has incompatible type "int"; expected "str" [list-item]
400-
a: List[str] = [0]
394+
a: list[str] = [0]
401395
402396
Check dict items [dict-item]
403397
----------------------------
@@ -410,10 +404,8 @@ Example:
410404

411405
.. code-block:: python
412406
413-
from typing import Dict
414-
415407
# Error: Dict entry 0 has incompatible type "str": "str"; expected "str": "int" [dict-item]
416-
d: Dict[str, int] = {'key': 'value'}
408+
d: dict[str, int] = {'key': 'value'}
417409
418410
Check TypedDict items [typeddict-item]
419411
--------------------------------------

docs/source/error_code_list2.rst

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -19,21 +19,19 @@ Check that type arguments exist [type-arg]
1919
------------------------------------------
2020

2121
If you use :option:`--disallow-any-generics <mypy --disallow-any-generics>`, mypy requires that each generic
22-
type has values for each type argument. For example, the types ``List`` or
23-
``dict`` would be rejected. You should instead use types like ``List[int]`` or
24-
``Dict[str, int]``. Any omitted generic type arguments get implicit ``Any``
25-
values. The type ``List`` is equivalent to ``List[Any]``, and so on.
22+
type has values for each type argument. For example, the types ``list`` or
23+
``dict`` would be rejected. You should instead use types like ``list[int]`` or
24+
``dict[str, int]``. Any omitted generic type arguments get implicit ``Any``
25+
values. The type ``list`` is equivalent to ``list[Any]``, and so on.
2626

2727
Example:
2828

2929
.. code-block:: python
3030
3131
# mypy: disallow-any-generics
3232
33-
from typing import List
34-
35-
# Error: Missing type parameters for generic type "List" [type-arg]
36-
def remove_dups(items: List) -> List:
33+
# Error: Missing type parameters for generic type "list" [type-arg]
34+
def remove_dups(items: list) -> list:
3735
...
3836
3937
Check that every function has an annotation [no-untyped-def]

0 commit comments

Comments
 (0)