-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
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
mypy deduces type as Optional after dict.get(x, x) #11337
Comments
I had a moment to dig into it. It is not releated to |
mypy probably still uses |
Not sure if it's minimally reproducing the same issue, but I found this example interesting: from typing import Optional, TypeVar, Union
T = TypeVar("T")
def f1(x: T) -> T:
return x
def f2(x: T) -> Union[str, T]:
return x
def g1(x: Optional[str]) -> None:
if x is None:
return
reveal_type(x) # Revealed type is "builtins.str"
x = f1(x)
reveal_type(x) # Revealed type is "builtins.str"
def g2(x: Optional[str]) -> None:
if x is None:
return
reveal_type(x) # Revealed type is "builtins.str"
x = f2(x)
reveal_type(x) # Revealed type is "Union[builtins.str, None]" EDIT:
OP's example also passes:
|
Another minimal example, not even using def foo(s: str) : ...
def bar(x: int, s: Optional[str] = None):
d: Dict[int, str] = {1: "a", 2: "b"}
if s is None:
s = d.get(x, "foo")
reveal_type(s)
f(s) mypy:
|
All examples have been fixed testing with the latest release. A Git bisect points to #14151 as the resolving PR. Thanks everyone for reporting! |
Bug Report
When calling
foo
s
is no longerOptional
and mypy gets this right when removingd.get(s, s)
. But it does not complain either withdef bar(s: str) -> None:
So from my understanding thed.get
is not the problem either.Expected Behavior
I would expect mypy to deduce that
foo(s)
is always called with astr
.Actual Behavior
mypy deduces
Optional[str]
Your Environment
mypy.ini
(and other config files):The text was updated successfully, but these errors were encountered: