-
-
Couldn't load subscription status.
- Fork 964
Use AnyStr where appropriate #999
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
Conversation
|
After this change... $ venv/bin/mypy example.py
Success: no issues found in 1 source file |
I don't think that's the case, either using import typing
AnyStrDict = typing.Dict[typing.AnyStr, typing.AnyStr]
AnyStrMapping = typing.Mapping[typing.AnyStr, typing.AnyStr]
d: AnyStrDict = {b"foo": "bar"}
m: AnyStrMapping = {b"foo": "bar"} |
|
Gotcha. It’s at least “consistent within this part of the type” tho right? Eg. Keys as str or Keys as bytes, not keys as str or bytes. |
|
Apparently not 😕 , again mypy is completely fine with the code below: import typing
AnyStrDict = typing.Dict[typing.AnyStr, typing.AnyStr]
AnyStrMapping = typing.Mapping[typing.AnyStr, typing.AnyStr]
d: AnyStrDict = {"foo": "bar", b"bar": "baz"}
m: AnyStrMapping = {b"foo": "bar", "foo": "baz"}Looks like the guarantees only hold in the context of a function. From the docs:
|
|
Interestingly from typing import Union, Dict, Sequence, Tuple, AnyStr
HeaderTypes = Union[
Dict[AnyStr, AnyStr], Sequence[Tuple[AnyStr, AnyStr]],
]
def foo(h: HeaderTypes) -> None:
print(h)
def bar(h: Union[Dict[AnyStr, AnyStr], Sequence[Tuple[AnyStr, AnyStr]]]) -> None:
print(h)
headers = {b"content-type": b"example", "accept": "*/*"}
foo(headers) # Ok
bar(headers) # Error |
Co-authored-by: Florimond Manca <[email protected]>
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
LGTM!
Refs #993, #985
Makes more careful use of
typing.Union[str, bytes]vs.typing.AnyStr.Use
AnyStrwhere we'd expect the types to be the same across everything in the signature. Eg.typing.Mapping[AnyStr, AnyStr]means "choose either str or bytes here, but be consistent.".Resolves an issues where mypy errors with a really simple bit of
httpxusage...example.py
MyPy