Skip to content

Replace List[X] with list[X] in docs #11450

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Nov 9, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions docs/source/additional_features.rst
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,10 @@ They can be defined using the :py:func:`@dataclasses.dataclass
@dataclass
class Application:
name: str
plugins: List[str] = field(default_factory=list)
plugins: list[str] = field(default_factory=list)

test = Application("Testing...") # OK
bad = Application("Testing...", "with plugin") # Error: List[str] expected
bad = Application("Testing...", "with plugin") # Error: list[str] expected

Mypy will detect special methods (such as :py:meth:`__lt__ <object.__lt__>`) depending on the flags used to
define dataclasses. For example:
Expand Down
39 changes: 20 additions & 19 deletions docs/source/cheat_sheet_py3.rst
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ Built-in types

.. code-block:: python


from typing import List, Set, Dict, Tuple, Optional

# For simple built-in types, just use the name of the type
Expand All @@ -60,16 +61,16 @@ Built-in types
x: set[int] = {6, 7}

# In Python 3.8 and earlier, the name of the collection type is
# capitalized, and the type is imported from 'typing'
# capitalized, and the type is imported from the 'typing' module
x: List[int] = [1]
x: Set[int] = {6, 7}

# Same as above, but with type comment syntax (Python 3.5 and earlier)
x = [1] # type: List[int]

# For mappings, we need the types of both keys and values
x: dict[str, float] = {'field': 2.0} # Python 3.9+
x: Dict[str, float] = {'field': 2.0}
x: dict[str, float] = {"field": 2.0} # Python 3.9+
x: Dict[str, float] = {"field": 2.0}

# For tuples of fixed size, we specify the types of all the elements
x: tuple[int, str, float] = (3, "yes", 7.5) # Python 3.9+
Expand All @@ -95,7 +96,7 @@ Python 3 supports an annotation syntax for function declarations.

.. code-block:: python

from typing import Callable, Iterator, Union, Optional, List
from typing import Callable, Iterator, Union, Optional

# This is how you annotate a function definition
def stringify(num: int) -> str:
Expand All @@ -121,12 +122,12 @@ Python 3 supports an annotation syntax for function declarations.
i += 1

# You can of course split a function annotation over multiple lines
def send_email(address: Union[str, List[str]],
def send_email(address: Union[str, list[str]],
sender: str,
cc: Optional[List[str]],
bcc: Optional[List[str]],
cc: Optional[list[str]],
bcc: Optional[list[str]],
subject='',
body: Optional[List[str]] = None
body: Optional[list[str]] = None
) -> bool:
...

Expand All @@ -143,23 +144,23 @@ When you're puzzled or when things are complicated

.. code-block:: python

from typing import Union, Any, List, Optional, cast
from typing import Union, Any, Optional, cast

# To find out what type mypy infers for an expression anywhere in
# your program, wrap it in reveal_type(). Mypy will print an error
# message with the type; remove it again before running the code.
reveal_type(1) # -> Revealed type is "builtins.int"

# Use Union when something could be one of a few types
x: List[Union[int, str]] = [3, 5, "test", "fun"]
x: list[Union[int, str]] = [3, 5, "test", "fun"]

# Use Any if you don't know the type of something or it's too
# dynamic to write a type for
x: Any = mystery_function()

# If you initialize a variable with an empty container or "None"
# you may have to help mypy a bit by providing a type annotation
x: List[str] = []
x: list[str] = []
x: Optional[str] = None

# This makes each positional arg and each keyword arg a "str"
Expand All @@ -176,8 +177,8 @@ When you're puzzled or when things are complicated
# "cast" is a helper function that lets you override the inferred
# type of an expression. It's only for mypy -- there's no runtime check.
a = [4]
b = cast(List[int], a) # Passes fine
c = cast(List[str], a) # Passes fine (no runtime check)
b = cast(list[int], a) # Passes fine
c = cast(list[str], a) # Passes fine (no runtime check)
reveal_type(c) # -> Revealed type is "builtins.list[builtins.str]"
print(c) # -> [4]; the object is not cast

Expand Down Expand Up @@ -209,25 +210,25 @@ that are common in idiomatic Python are standardized.

.. code-block:: python

from typing import Mapping, MutableMapping, Sequence, Iterable, List, Set
from typing import Mapping, MutableMapping, Sequence, Iterable

# Use Iterable for generic iterables (anything usable in "for"),
# and Sequence where a sequence (supporting "len" and "__getitem__") is
# required
def f(ints: Iterable[int]) -> List[str]:
def f(ints: Iterable[int]) -> list[str]:
return [str(x) for x in ints]

f(range(1, 3))

# Mapping describes a dict-like object (with "__getitem__") that we won't
# mutate, and MutableMapping one (with "__setitem__") that we might
def f(my_mapping: Mapping[int, str]) -> List[int]:
def f(my_mapping: Mapping[int, str]) -> list[int]:
my_mapping[5] = 'maybe' # if we try this, mypy will throw an error...
return list(my_mapping.keys())

f({3: 'yes', 4: 'no'})

def f(my_mapping: MutableMapping[int, str]) -> Set[str]:
def f(my_mapping: MutableMapping[int, str]) -> set[str]:
my_mapping[5] = 'maybe' # ...but mypy is OK with this.
return set(my_mapping.values())

Expand Down Expand Up @@ -262,12 +263,12 @@ Classes
# You can use the ClassVar annotation to declare a class variable
class Car:
seats: ClassVar[int] = 4
passengers: ClassVar[List[str]]
passengers: ClassVar[list[str]]

# You can also declare the type of an attribute in "__init__"
class Box:
def __init__(self) -> None:
self.items: List[str] = []
self.items: list[str] = []


Coroutines and asyncio
Expand Down
10 changes: 5 additions & 5 deletions docs/source/class_basics.rst
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ a type annotation:
.. code-block:: python

class A:
x: List[int] # Declare attribute 'x' of type List[int]
x: list[int] # Declare attribute 'x' of type list[int]

a = A()
a.x = [1] # OK
Expand All @@ -48,7 +48,7 @@ than 3.6:
.. code-block:: python

class A:
x = None # type: List[int] # Declare attribute 'x' of type List[int]
x = None # type: list[int] # Declare attribute 'x' of type list[int]

Note that attribute definitions in the class body that use a type comment
are special: a ``None`` value is valid as the initializer, even though
Expand All @@ -62,7 +62,7 @@ in a method:

class A:
def __init__(self) -> None:
self.x: List[int] = []
self.x: list[int] = []

def f(self) -> None:
self.y: Any = 0
Expand Down Expand Up @@ -160,7 +160,7 @@ This behavior will change in the future, since it's surprising.

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

Expand Down Expand Up @@ -200,7 +200,7 @@ override has a compatible signature:

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

You can also override a statically typed method with a dynamically
Expand Down
15 changes: 7 additions & 8 deletions docs/source/command_line.rst
Original file line number Diff line number Diff line change
Expand Up @@ -312,9 +312,8 @@ The following options are available:
.. option:: --disallow-any-generics

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

.. option:: --disallow-subclassing-any

Expand Down Expand Up @@ -521,10 +520,10 @@ of the above sections.

.. code-block:: python

def process(items: List[str]) -> None:
# 'items' has type List[str]
def process(items: list[str]) -> None:
# 'items' has type list[str]
items = [item.split() for item in items]
# 'items' now has type List[List[str]]
# 'items' now has type list[list[str]]
...

.. option:: --local-partial-types
Expand Down Expand Up @@ -585,9 +584,9 @@ of the above sections.

.. code-block:: python

from typing import List, Text
from typing import Text

items: List[int]
items: list[int]
if 'some string' in items: # Error: non-overlapping container check!
...

Expand Down
68 changes: 30 additions & 38 deletions docs/source/error_code_list.rst
Original file line number Diff line number Diff line change
Expand Up @@ -117,15 +117,15 @@ Example:

.. code-block:: python

from typing import List, Optional
from typing import Optional

def first(x: List[int]) -> Optional[int]:
def first(x: list[int]) -> Optional[int]:
return x[0] if x else 0

t = (5, 4)
# Error: Argument 1 to "first" has incompatible type "Tuple[int, int]";
# expected "List[int]" [arg-type]
print(first(t))
t = (5, 4)
# Error: Argument 1 to "first" has incompatible type "tuple[int, int]";
# expected "list[int]" [arg-type]
print(first(t))

Check calls to overloaded functions [call-overload]
---------------------------------------------------
Expand Down Expand Up @@ -171,26 +171,24 @@ This example incorrectly uses the function ``log`` as a type:

.. code-block:: python

from typing import List
def log(x: object) -> None:
print('log:', repr(x))

def log(x: object) -> None:
print('log:', repr(x))

# Error: Function "t.log" is not valid as a type [valid-type]
def log_all(objs: List[object], f: log) -> None:
for x in objs:
f(x)
# Error: Function "t.log" is not valid as a type [valid-type]
def log_all(objs: list[object], f: log) -> None:
for x in objs:
f(x)

You can use :py:data:`~typing.Callable` as the type for callable objects:

.. code-block:: python

from typing import List, Callable
from typing import Callable

# OK
def log_all(objs: List[object], f: Callable[[object], None]) -> None:
for x in objs:
f(x)
# OK
def log_all(objs: list[object], f: Callable[[object], None]) -> None:
for x in objs:
f(x)

Require annotation if variable type is unclear [var-annotated]
--------------------------------------------------------------
Expand All @@ -206,23 +204,21 @@ Example with an error:

.. code-block:: python

class Bundle:
def __init__(self) -> None:
# Error: Need type annotation for "items"
# (hint: "items: List[<type>] = ...") [var-annotated]
self.items = []
class Bundle:
def __init__(self) -> None:
# Error: Need type annotation for "items"
# (hint: "items: list[<type>] = ...") [var-annotated]
self.items = []

reveal_type(Bundle().items) # list[Any]
reveal_type(Bundle().items) # list[Any]

To address this, we add an explicit annotation:

.. code-block:: python

from typing import List

class Bundle:
def __init__(self) -> None:
self.items: List[str] = [] # OK
class Bundle:
def __init__(self) -> None:
self.items: list[str] = [] # OK

reveal_type(Bundle().items) # list[str]

Expand Down Expand Up @@ -377,10 +373,10 @@ Example:

a['x'] # OK

# Error: Invalid index type "int" for "Dict[str, int]"; expected type "str" [index]
# Error: Invalid index type "int" for "dict[str, int]"; expected type "str" [index]
print(a[1])

# Error: Invalid index type "bytes" for "Dict[str, int]"; expected type "str" [index]
# Error: Invalid index type "bytes" for "dict[str, int]"; expected type "str" [index]
a[b'x'] = 4

Check list items [list-item]
Expand All @@ -394,10 +390,8 @@ Example:

.. code-block:: python

from typing import List

# Error: List item 0 has incompatible type "int"; expected "str" [list-item]
a: List[str] = [0]
a: list[str] = [0]

Check dict items [dict-item]
----------------------------
Expand All @@ -410,10 +404,8 @@ Example:

.. code-block:: python

from typing import Dict

# Error: Dict entry 0 has incompatible type "str": "str"; expected "str": "int" [dict-item]
d: Dict[str, int] = {'key': 'value'}
d: dict[str, int] = {'key': 'value'}

Check TypedDict items [typeddict-item]
--------------------------------------
Expand Down
14 changes: 6 additions & 8 deletions docs/source/error_code_list2.rst
Original file line number Diff line number Diff line change
Expand Up @@ -19,21 +19,19 @@ Check that type arguments exist [type-arg]
------------------------------------------

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

Example:

.. code-block:: python

# mypy: disallow-any-generics

from typing import List

# Error: Missing type parameters for generic type "List" [type-arg]
def remove_dups(items: List) -> List:
# Error: Missing type parameters for generic type "list" [type-arg]
def remove_dups(items: list) -> list:
...

Check that every function has an annotation [no-untyped-def]
Expand Down
Loading