Skip to content

Describe how to annotate a function with return type depending on a flag #13884

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

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
21 changes: 21 additions & 0 deletions docs/source/more_types.rst
Original file line number Diff line number Diff line change
Expand Up @@ -307,6 +307,27 @@ redundancy, it's possible to replace default values in overload definitions with
def get_model(model_or_pk: int | M, flag: bool = True) -> M | None:
...

The overload that applies is chosen depending on the type of the ``model_or_pk``
argument. On the other hand, the return type in the following example depends on
an argument with a default value. To ensure that the overloads do not overlap,
a default value is specified for only one of them.

.. code-block:: python

from typing import overload, Literal

# This overload variant applies only when the "rounded" argument was
# specified explicitly.
@overload
def pi(rounded: Literal[True]) -> int: ...

# This overload variant applies when "rounded" is omitted or set to False.
@overload
def pi(rounded: Literal[False] = ...) -> float: ...

def pi(rounded=False):
return 3 if rounded else 3.14159


Runtime behavior
----------------
Expand Down