-
-
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
Cannot call dict.get with a falsy second argument and an 'or' expression. #5519
Comments
Note that plain (i.e. without type context) reveal_type(d.get('key', None) or '26') # No error, revealed type is 'builtins.str' So I can guess this is a weird variation of #4872 which is already high priority. |
Should this really be viewed as an error? It depends on whether you would like to expect that dict.get should always return the type of the value ( foo(d.get('key', '') or '26') |
That shouldn't matter, though. Regardless of the fact that you can work around it, it is still impossible to have mismatched types in this code, making the error incorrect. |
Yep, you're right. I was assuming that the default argument should be of the same type as the value type of the dict ( |
It turns out this is unrelated to #4872. The fix is simple but it involves compromises, so we need to wait a bit more to see how often this error appears. |
@ilevkivskyi would you mind explaining what the compromises are? |
One way to solve: provide an optional context for inference -- downside: it looks too ad-hoc. |
I seem to be getting a possibly-related error where mypy fails to eliminate the from typing import Dict, List, Optional, Iterable
class C:
def __init__(self) -> None:
self.sources: Dict[str, List[str]] = {}
def process(self, name: str, sources: Optional[Iterable[str]] = None) -> None:
reveal_type(sources)
reveal_type(self.sources.get(name, []))
reveal_type(sources or self.sources.get(name, []))
to_process: Iterable[str] = sources or self.sources.get(name, [])
print(to_process) Running y.py:8: error: Revealed type is 'Union[typing.Iterable[builtins.str], None]'
y.py:9: error: Revealed type is 'builtins.list[builtins.str]'
y.py:10: error: Revealed type is 'Union[typing.Iterable[builtins.str], None]'
y.py:11: error: Incompatible types in assignment (expression has type "Optional[Iterable[str]]", variable has type "Iterable[str]") |
In mypy 0.610, as well as the latest version from master, the following throws an error under Python 3.6
test.py:6: error: Argument 2 to "get" of "Mapping" has incompatible type "None"; expected "str"
However, no matter what,
foo
will still receive astr
, given thatNone
is falsy. Therefore, no error should be thrown. This occurs with just a simple call tomypy foo.py
with no flags.The text was updated successfully, but these errors were encountered: