-
Notifications
You must be signed in to change notification settings - Fork 766
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
Match not type guarding TypedDicts #4248
Comments
To repro this, I need to enable strict mode type checking, or at least enable The current behavior is by design. Pyright, the type checker that underlies pylance, performs type narrowing of the subject expression in match statements. In this case, the subject expression is for item in my_list:
match item["name"]:
case "foo" as x:
reveal_type(x) # Literal["foo"]
case "bar" as y:
reveal_type(y) # Literal["bar"] Your code is relying on narrowing of We could look at adding such support in the future if there was sufficient demand, but I suspect that it would be expensive from an analysis standpoint. If it affects analysis performance in the general case, it wouldn't be a good tradeoff to support this particular pattern. Pyright does support TypedDict discrimination when using certain forms for item in my_list:
if item["name"] == "foo":
print(item["extra_value"])
elif item["name"] == "bar":
print(item["other_extra_value"]) |
Thank you for the thorough reply Eric 😄 I did initially start with an I'm happy to close if you think this is intended behaviour! |
If you want to want to use a for item in my_list:
match item:
case {"name": "foo"}:
print(item["extra_value"])
case {"name": "bar"}:
print(item["other_extra_value"]) Let's leave the issue open for now. I'll give your feature request a bit more thought. |
Oh, that's really interesting! I'll have to brush up on my knowledge of match statements but that does indeed work 😃 |
BTW, if you want to use exhaustive matching with for item in my_list:
if item["name"] == "foo":
print(item["extra_value"])
elif item["name"] == "bar":
print(item["other_extra_value"])
else:
assert_never(item) |
That's actually super helpful, thank you once again! |
…ject expression for match statements. In particular, added support for discriminated TypedDicts and tuples that are discriminated on literals. This addresses microsoft/pylance-release#4248.
I figured out a way to handle this is a way that doesn't have a measurable impact on performance. It will be included in the next release of pyright and a future release of pylance. |
You wizard, my code thanks you for the quick turnaround 😄 |
Pylance |
Environment data
Code Snippet
Repro Steps
Expected behavior
Line 26 should type guard item so that it's of type
Derived
and line 30 should type guard item so that it's of typeMegaDerived
Actual behavior
The type hint for item remains unchanged as
Derived | MegaDerived
Logs
The text was updated successfully, but these errors were encountered: