Skip to content

Commit 354af8a

Browse files
committed
Describe how to annotate functions whose return type depends on an optional argument
I could not find how to do this in the documentation, but eventually saw the example in python#6580 (comment)
1 parent 7cc024a commit 354af8a

1 file changed

Lines changed: 21 additions & 0 deletions

File tree

‎docs/source/more_types.rst‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -307,6 +307,27 @@ redundancy, it's possible to replace default values in overload definitions with
307307
def get_model(model_or_pk: int | M, flag: bool = True) -> M | None:
308308
...
309309
310+
The overload that applies is chosen depending on the type of the ``model_or_pk``
311+
argument. On the other hand, the return type in the following example depends on
312+
an argument with a default value. To ensure that the overloads do not overlap,
313+
a default value is specified for only one of them.
314+
315+
.. code-block:: python
316+
317+
from typing import overload, Literal
318+
319+
# This overload variant applies when "rounded" is omitted or set to False.
320+
@overload
321+
def pi(rounded: Literal[False] = ...) -> float: ...
322+
323+
# This overload variant applies only when the "rounded" argument was
324+
# specified explicitly.
325+
@overload
326+
def pi(rounded: Literal[True]) -> int: ...
327+
328+
def pi(rounded=False):
329+
return 3 if rounded else 3.14159
330+
310331
311332
Runtime behavior
312333
----------------

0 commit comments

Comments
 (0)