Skip to content

Commit

Permalink
Describe how to annotate functions whose return type depends on an op…
Browse files Browse the repository at this point in the history
…tional argument

I could not find how to do this in the documentation, but eventually saw the
example in
python#6580 (comment)
  • Loading branch information
marcelm committed Oct 13, 2022
1 parent 7cc024a commit 354af8a
Showing 1 changed file with 21 additions and 0 deletions.
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 when "rounded" is omitted or set to False.
@overload
def pi(rounded: Literal[False] = ...) -> float: ...
# This overload variant applies only when the "rounded" argument was
# specified explicitly.
@overload
def pi(rounded: Literal[True]) -> int: ...
def pi(rounded=False):
return 3 if rounded else 3.14159
Runtime behavior
----------------
Expand Down

0 comments on commit 354af8a

Please sign in to comment.