Thanks to visit codestin.com
Credit goes to github.com

Skip to content
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
23 changes: 12 additions & 11 deletions docs/source/cheat_sheet_py3.rst
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,9 @@ Useful built-in types
# On earlier versions, use Union
x: list[Union[int, str]] = [3, 5, "test", "fun"]

# Use Optional[X] for a value that could be None
# Optional[X] is the same as X | None or Union[X, None]
x: Optional[str] = "something" if some_condition() else None
# Use X | None for a value that could be None on Python 3.10+
# Use Optional[X] on 3.9 and earlier; Optional[X] is the same as 'X | None'
x: str | None = "something" if some_condition() else None
if x is not None:
# Mypy understands x won't be None here because of the if-statement
print(x.upper())
Expand Down Expand Up @@ -122,13 +122,14 @@ Functions
i += 1

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

# Mypy understands positional-only and keyword-only arguments
Expand Down Expand Up @@ -231,7 +232,7 @@ When you're puzzled or when things are complicated
# If you initialize a variable with an empty container or "None"
# you may have to help mypy a bit by providing an explicit type annotation
x: list[str] = []
x: Optional[str] = None
x: str | None = None

# Use Any if you don't know the type of something or it's too
# dynamic to write a type for
Expand Down
18 changes: 8 additions & 10 deletions docs/source/command_line.rst
Original file line number Diff line number Diff line change
Expand Up @@ -420,11 +420,11 @@ The following flags adjust how mypy handles values of type ``None``.

.. option:: --implicit-optional

This flag causes mypy to treat arguments with a ``None``
default value as having an implicit :py:data:`~typing.Optional` type.
This flag causes mypy to treat parameters with a ``None``
default value as having an implicit optional type (``T | None``).

For example, if this flag is set, mypy would assume that the ``x``
parameter is actually of type ``Optional[int]`` in the code snippet below
parameter is actually of type ``int | None`` in the code snippet below,
since the default parameter is ``None``:

.. code-block:: python
Expand All @@ -438,7 +438,7 @@ The following flags adjust how mypy handles values of type ``None``.

.. option:: --no-strict-optional

This flag effectively disables checking of :py:data:`~typing.Optional`
This flag effectively disables checking of optional
types and ``None`` values. With this option, mypy doesn't
generally check the use of ``None`` values -- it is treated
as compatible with every type.
Expand Down Expand Up @@ -575,26 +575,24 @@ of the above sections.
.. option:: --local-partial-types

In mypy, the most common cases for partial types are variables initialized using ``None``,
but without explicit ``Optional`` annotations. By default, mypy won't check partial types
but without explicit ``X | None`` annotations. By default, mypy won't check partial types
spanning module top level or class top level. This flag changes the behavior to only allow
partial types at local level, therefore it disallows inferring variable type for ``None``
from two assignments in different scopes. For example:

.. code-block:: python

from typing import Optional

a = None # Need type annotation here if using --local-partial-types
b: Optional[int] = None
b: int | None = None

class Foo:
bar = None # Need type annotation here if using --local-partial-types
baz: Optional[int] = None
baz: int | None = None

def __init__(self) -> None:
self.bar = 1

reveal_type(Foo().bar) # Union[int, None] without --local-partial-types
reveal_type(Foo().bar) # 'int | None' without --local-partial-types

Note: this option is always implicitly enabled in mypy daemon and will become
enabled by default for mypy in a future release.
Expand Down
2 changes: 1 addition & 1 deletion docs/source/common_issues.rst
Original file line number Diff line number Diff line change
Expand Up @@ -803,7 +803,7 @@ This is best understood via an example:

.. code-block:: python

def foo(x: Optional[int]) -> Callable[[], int]:
def foo(x: int | None) -> Callable[[], int]:
if x is None:
x = 5
print(x + 1) # mypy correctly deduces x must be an int here
Expand Down
6 changes: 3 additions & 3 deletions docs/source/config_file.rst
Original file line number Diff line number Diff line change
Expand Up @@ -574,8 +574,8 @@ section of the command line docs.
:type: boolean
:default: False

Causes mypy to treat arguments with a ``None``
default value as having an implicit :py:data:`~typing.Optional` type.
Causes mypy to treat parameters with a ``None``
default value as having an implicit optional type (``T | None``).

**Note:** This was True by default in mypy versions 0.980 and earlier.

Expand All @@ -584,7 +584,7 @@ section of the command line docs.
:type: boolean
:default: True

Effectively disables checking of :py:data:`~typing.Optional`
Effectively disables checking of optional
types and ``None`` values. With this option, mypy doesn't
generally check the use of ``None`` values -- it is treated
as compatible with every type.
Expand Down
20 changes: 7 additions & 13 deletions docs/source/error_code_list.rst
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,6 @@ Example:

.. code-block:: python

from typing import Union

class Cat:
def sleep(self) -> None: ...
def miaow(self) -> None: ...
Expand All @@ -69,10 +67,10 @@ Example:
def sleep(self) -> None: ...
def follow_me(self) -> None: ...

def func(animal: Union[Cat, Dog]) -> None:
def func(animal: Cat | Dog) -> None:
# OK: 'sleep' is defined for both Cat and Dog
animal.sleep()
# Error: Item "Cat" of "Union[Cat, Dog]" has no attribute "follow_me" [union-attr]
# Error: Item "Cat" of "Cat | Dog" has no attribute "follow_me" [union-attr]
animal.follow_me()

You can often work around these errors by using ``assert isinstance(obj, ClassName)``
Expand Down Expand Up @@ -142,9 +140,7 @@ Example:

.. code-block:: python

from typing import Optional

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

t = (5, 4)
Expand All @@ -165,15 +161,15 @@ Example:

.. code-block:: python

from typing import overload, Optional
from typing import overload

@overload
def inc_maybe(x: None) -> None: ...

@overload
def inc_maybe(x: int) -> int: ...

def inc_maybe(x: Optional[int]) -> Optional[int]:
def inc_maybe(x: int | None) -> int | None:
if x is None:
return None
else:
Expand Down Expand Up @@ -273,16 +269,14 @@ Example:

.. code-block:: python

from typing import Optional, Union

class Base:
def method(self,
arg: int) -> Optional[int]:
arg: int) -> int | None:
...

class Derived(Base):
def method(self,
arg: Union[int, str]) -> int: # OK
arg: int | str) -> int: # OK
...

class DerivedBad(Base):
Expand Down
6 changes: 3 additions & 3 deletions docs/source/generics.rst
Original file line number Diff line number Diff line change
Expand Up @@ -571,9 +571,9 @@ Let us illustrate this by few simple examples:
class Square(Shape): ...

* Most immutable container types, such as :py:class:`~collections.abc.Sequence`
and :py:class:`~frozenset` are covariant. :py:data:`~typing.Union` is
also covariant in all variables: ``Union[Triangle, int]`` is
a subtype of ``Union[Shape, int]``.
and :py:class:`~frozenset` are covariant. Union types are
also covariant in all union items: ``Triangle | int`` is
a subtype of ``Shape | int``.

.. code-block:: python

Expand Down
16 changes: 10 additions & 6 deletions docs/source/getting_started.rst
Original file line number Diff line number Diff line change
Expand Up @@ -186,19 +186,23 @@ For example, a ``RuntimeError`` instance can be passed to a function that is ann
as taking an ``Exception``.

As another example, suppose you want to write a function that can accept *either*
ints or strings, but no other types. You can express this using the
:py:data:`~typing.Union` type. For example, ``int`` is a subtype of ``Union[int, str]``:
ints or strings, but no other types. You can express this using a
union type. For example, ``int`` is a subtype of ``int | str``:

.. code-block:: python

from typing import Union

def normalize_id(user_id: Union[int, str]) -> str:
def normalize_id(user_id: int | str) -> str:
if isinstance(user_id, int):
return f'user-{100_000 + user_id}'
else:
return user_id

.. note::

If using Python 3.9 or earlier, use ``typing.Union[int, str]`` instead of
``int | str``, or use ``from __future__ import annotations`` at the top of
the file (see :ref:`runtime_troubles`).

The :py:mod:`typing` module contains many other useful types.

For a quick overview, look through the :ref:`mypy cheatsheet <cheat-sheet-py3>`.
Expand All @@ -210,7 +214,7 @@ generic types or your own type aliases), look through the
.. note::

When adding types, the convention is to import types
using the form ``from typing import Union`` (as opposed to doing
using the form ``from typing import <name>`` (as opposed to doing
just ``import typing`` or ``import typing as t`` or ``from typing import *``).

For brevity, we often omit imports from :py:mod:`typing` or :py:mod:`collections.abc`
Expand Down
Loading