-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Support type narrowing literals using typing.get_args()
#15106
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
+1 to this. I had wanted to use You can do this: from typing import Literal, Optional
ValidToken = Literal["foo", "bar", "baz"]
def parse_token(s: str) -> Optional[ValidToken]:
if s == "foo" or s == "bar" or s == "baz":
return s
else:
return None
if __name__ == "__main__":
user_input = input()
token = parse_token(user_input) # token has type Optional[ValidToken] But this requires laboriously writing out the members of the union in duplicate. And you have to update it in both places when you add or remove members. If we could use Would be even cooler if it could somehow be made to work like |
I've just hit the desire to do this as well. I have a little time and I'm up for taking a run at and see if it's not too hard to do.
I took a quick look at microsoft/pyright#5837 which is similar. Based on that pyright already supports the narrowing part. Though there wasn't much support for adding the
Assuming the type narrowing isn't objectionable it seems the main question is how to handle Thoughts? |
That makes sense. Your (1) has a number of open issues about it already (I think #3229 is the oldest) and should be implemented independently. Once that is done, we can look into special handling for |
Feature
When using
typing.get_args()
to ensure that a given string is of a literal type, I would expect mypy to behave similarly than whenisinstance()
checks are used.Pitch
Take the following code:
Mypy does not detect that the string must be of the correct type, since the code path is unreachable for an invalid value and outputs an error, requiring the use of casts even though the value is guaranteed to be of the correct type:
The text was updated successfully, but these errors were encountered: