Skip to content

Commit 97270d7

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 97270d7

1 file changed

Lines changed: 22 additions & 0 deletions

File tree

‎docs/source/more_types.rst‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -307,6 +307,28 @@ 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+
When a function's return type depends on an argument with a default value, a
311+
separate overload without the optional argument is needed.
312+
313+
.. code-block:: python
314+
315+
from typing import overload, Literal
316+
317+
@overload
318+
def pi(rounded: Literal[True]) -> int: ...
319+
320+
@overload
321+
def pi(rounded: Literal[False]) -> float: ...
322+
323+
# The following overload variant applies when the 'rounded' parameter is
324+
# omitted.
325+
326+
@overload
327+
def pi() -> float: ...
328+
329+
def pi(rounded=False):
330+
return 3 if rounded else 3.14159
331+
310332
311333
Runtime behavior
312334
----------------

0 commit comments

Comments
 (0)