-
Notifications
You must be signed in to change notification settings - Fork 1.5k
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
"bool" cannot be assigned to type "Literal[False]" in calling an overloaded function from an overloaded function #5230
Comments
Yes, this is correct. You have defined two overloads, and they accept only @overload
@classmethod
def from_something_else(cls, return_two: bool) -> int | tuple[int, int]:
... Pyright doesn't expand |
type checkers won't infer Union[Literal[True], Literal[False]] in this case, so we need to manually define it microsoft/pyright#5230
I am working in the following example file, and I feel like I am missing something: from typing import Literal, overload
@overload
def f(a: Literal[True]) -> int: ...
@overload
def f(a: Literal[False]) -> str: ...
# @overload
# def f(a: bool) -> int | str: ...
def f(a: bool) -> int | str:
return 1 if a else '1'
f(a=True)
f(a=False)
def g(a: bool = True) -> int:
return int(f(a=a)) If i execute
But if I uncomment commented lines everything is fine. I do not understand:
Could you provide any help on this?. Thank you in advance. PD: I am using pyright 1.1.373 on Windows laptop (just in case) |
Calling it inside versus outside a function is irrelevant. What is relevant is whether you're calling it with an argument that has type from random import random
x = random() > 0.5
reveal_type(x) # bool
f(a=x) # Error
f(a=True) # No error
When a call expression is evaluated by a type checker and the callee is overloaded, only the overload signatures are considered by a type checker. The implementation is ignored in this case. For details, refer to the overload description in the official Python typing spec. Not surprisingly, the other major Python type checkers including mypy behave the same with your code sample. |
I recently submitted a draft update to the Python typing spec that clarifies the type checker behaviors for argument type expansion when evaluating calls to overloaded functions. The draft spec includes expansion of This draft update hasn't yet been approved by the full Typing Council, but I think there's a good chance it will be in the near future. |
Describe the bug
When I have 2
classmethod
s overloaded on abool
, when I call one from the other, it says thatbool
cannot be assigned toLiteral[X]
whereX
is the 2nd overload signature (Literal[False]
) below.To Reproduce
Expected behavior
I do not expect to see this error message.
VS Code extension or command-line
Pylance for VS Code v2023.5.50
The text was updated successfully, but these errors were encountered: