-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Type Narrowing for Dictionary Keys Not Working with Literal Types After in Check #18208
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
Comments
I am having a similar issue with the below code. from typing import Optional
def func(X: str, Y: str):
print(f"{X} : {Y}")
my_dict: dict[str, Optional[str]] = {"this": None, "that": "T"}
idx: str = "that"
if my_dict[idx] is None:
raise ValueError(f"my_dict[{idx}] is None")
if idx not in my_dict:
raise ValueError(f"{idx} does not exist in my_dict")
if not isinstance(my_dict[idx], str):
raise ValueError(f"my_dict[{idx}] is not a string")
func(my_dict[idx], "YYY") I have a dictionary with a key type "str" and it looks like no check ever can get rid of the warning: main.py:19: error: Argument 1 to "func" has incompatible type "str | None"; expected "str" [arg-type] Playground link: https://mypy-play.net/?mypy=latest&python=3.11&gist=7141a47bd7fc21c0ebe82c639db5188e Not sure if this is the same issue. If it is not - please let me know and I can open a separate issue. |
Thank you for sharing this issue. As a mypy user, I find myself in a similar situation, and while I can't be completely certain, your case seems distinct from the original example. It might be worth reporting separately. My Considerations:
|
Is this the same as #3229? |
No, not exactly the same, I guess... |
Bug Report
Mypy fails to narrow the type of a dictionary key from
str
to aLiteral
type even after an existence check within
operator. This pattern is commonly used and type-safe, as the runtime check guarantees the key exists and thus must be one of the literal values.To Reproduce
Playground link: https://mypy-play.net/?mypy=latest&python=3.11&gist=92110930ab70a8949ae51cbcf8b8cb5f
Expected Behavior
After checking
key in data
, mypy should recognize thatkey
must be one of the literal values defined inKeyType
since it exists as a key in the dictionary. Therefore, the dictionary accessdata[key]
should type-check successfully.Actual Behavior
Your Environment
The text was updated successfully, but these errors were encountered: