-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Document when to use Union[str, unicode] vs AnyStr #871
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'm new to this project so please correct me if I've asked this question in the wrong place.) The xml.etree module documents the return type of tostring() in python 3 as either str (if the value of the However, the tostring stub documents it returning simply str.
This is a blocker to usage in python 3 since the return type is just wrong for many use cases. Should this stubfile be changed to return AnyStr, or a Union, or something else entirely? (Am happy to submit a PR to do this but I'm not sure which you would do.) |
@lincolnq In cases like these typeshed typically uses an |
I started writing documentation to address this issue; what I have so far is at master...JelleZijlstra:patch-10 (heavily based on Jukka's comments here). However, I don't understand what Jukka is referring to in his paragraph about type arguments: "For example, |
I think we have sufficient documentation when to use |
This comes up pretty often, and it would be useful to have some documentation in the CONTRIBUTING.md file (or at least a link to this documentation).
Here's a starting point for what to document (there probably are other things that we should mention):
str
and ascii-onlyunicode
arguments, usually the best type to use isUnion[str, unicode]
(orUnion[str, Text]
in a 2and3 stub).AnyStr
if you have two or more types in a signature that must agree on whether they arestr
orunicode
. (It would also be nice to give an example where this is important.)AnyStr
in invariant positions in generic type arguments. For example,List[AnyStr]
is generally better thanList[Union[str, unicode]]
(also explain why). However, often it's even better to use a covariant type such asIterable
orSequence
. In that case the union variant is preferable if the container may contain a mix ofstr
andunicode
. For example,Iterable[Union[str, unicode]]
is fine if the iterable may contain a mix ofstr
andunicode
values.Union[str, unicode]
in a return type, since it means that every call site will have to deal with bothstr
andunicode
values. It may be fine to use this if the return type is sufficiently unpredictable.Union[str, unicode]
as an attribute type -- again code using this attribute would have to deal with bothstr
andunicode
values.The text was updated successfully, but these errors were encountered: