Replies: 1 comment 3 replies
-
The Python type system includes the concept of an "overload", which allows you to specify polymorphic function behaviors where a function's return type depends on the types of its parameters. Here's how that would be done with your example: from typing import Literal, overload
class Foo:
pass
@overload
def bar(additional_data: Literal[True]) -> tuple[float, Foo]: ...
@overload
def bar(additional_data: Literal[False] = False) -> float: ...
def bar(additional_data: bool = False) -> float | tuple[float, Foo]:
if additional_data:
return 1, Foo()
else:
return 1
a = bar(False)
b, c = bar(True) For more details, refer to the Python typing spec. |
Beta Was this translation helpful? Give feedback.
3 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hello,
Given the following code, that uses a function with a varying return type:
Pyright produces the following error:
I know I can do a check on the return value as follows to prevent the error:
I was wondering however if there is another way?
Beta Was this translation helpful? Give feedback.
All reactions