-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
os.open should not have AnyStr in its type #439
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
Should type checkers just detect a single usage and optimize for it? AnyStr is a pretty convenient shortcut. |
I'm not convinced that would actually be correct, under the semantics specified in PEP 484. The semantics of
We're trying to use a value of type The type Does that match your interpretation of the semantics? How would you interpret PEP 484 in the context of this code that makes it well-typed? |
I had assumed that With that, your code sample passes checking, based on |
No, (Constrained type variables are tricky that way. It took me a long time to grok them. And I still haven't found an example besides I'm still not sure how to express what I'd like to see, and maybe it's not worth it. We can't exactly say that |
In order to unify these two versions I'm making all paths be _PathType = Union[bytes, Text] Fixes python#439
It seems that AnyStr has the main advantage of ensuring that multiple arguments (or argument(s) and return values) have the same type (i.e. `str` and `bytes` are both okay but shouldn't be mixed). However it makes it significantly more difficult to cast to a single type. With a Union, something like: ```python def foo(a: Union[bytes, Text]) -> Text: if isinstance(a, bytes): a = a.decode() return "Hello, " + a ``` works fine. With AnyStr, you have to define a new intermediate variable, something like: ```python def foo(a: AnyStr) -> str: if isinstance(a, bytes): b = a.decode() else: b = a return "Hello, " + b ``` If there's no advantage to using AnyStr (since there's no other AnyStr argument or return value), I think the Union would be simpler, have no significant disadvantage, and there is [precedent for similar changes](python#1054). > It's only the case that if there's exactly one parameter of type exactly AnyStr, and no other use of AnyStr in the signature, then Union[str, bytes] should be acceptable. - [gvanrossum](python#439 (comment)) Discussion: - python#1054 - python/mypy#1141 - python#439
See python/mypy#1943 --
AnyStr
shouldn't be used when it only appears once in the type, because it complicates the semantics without adding anything.The text was updated successfully, but these errors were encountered: