Skip to content

DOC: update documentation of type annotation (PEP 585) #44948

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
Dec 19, 2021
Merged
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
22 changes: 16 additions & 6 deletions doc/source/development/contributing_codebase.rst
Original file line number Diff line number Diff line change
Expand Up @@ -303,7 +303,7 @@ pandas strongly encourages the use of :pep:`484` style type hints. New developme
Style guidelines
~~~~~~~~~~~~~~~~

Types imports should follow the ``from typing import ...`` convention. So rather than
Type imports should follow the ``from typing import ...`` convention. Some types do not need to be imported since :pep:`585` some builtin constructs, such as ``list`` and ``tuple``, can directly be used for type annotations. So rather than

.. code-block:: python

Expand All @@ -315,21 +315,31 @@ You should write

.. code-block:: python

from typing import List, Optional, Union
primes: list[int] = []

primes: List[int] = []
``Optional`` should be avoided in favor of the shorter ``| None``, so instead of

``Optional`` should be used where applicable, so instead of
.. code-block:: python

from typing import Union

maybe_primes: list[Union[int, None]] = []

or

.. code-block:: python

maybe_primes: List[Union[int, None]] = []
from typing import Optional

maybe_primes: list[Optional[int]] = []

You should write

.. code-block:: python

maybe_primes: List[Optional[int]] = []
from __future__ import annotations # noqa: F404

maybe_primes: list[int | None] = []

In some cases in the code base classes may define class variables that shadow builtins. This causes an issue as described in `Mypy 1775 <https://github.com/python/mypy/issues/1775#issuecomment-310969854>`_. The defensive solution here is to create an unambiguous alias of the builtin and use that without your annotation. For example, if you come across a definition like

Expand Down