-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Document how (not) to use basestring #1537
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
See also python/typeshed#138 |
This comes up in attempting to make python-3 compatible code with import six
from typing import Any
def c(a, b): # type: (Any, Any) -> int
if isinstance(a, six.string_types):
return getattr(b, a)
else:
return b[a] This fails with:
I think updating the type signature in the stub type of |
What is Python 2? |
Users have started using
basestring
in stubs and elsewhere. Usingbasestring
as a function argument type in a stub seems relatively benign (though inconsistent), but using as a return type is problematic for a few reasons:basestring
currently has no operations and can't be passed to functions expectingunicode
or evenUnion[bytes, unicode]
.isinstance()
doesn't work well, since it's not a union. It's often necessary to use something likeif isinstance(x, bytes): ... elif isinstance(x, unicode)
instead ofif isinstance(x, bytes): ... else: ...
.Not sure what we should tell users. Perhaps say that using
basestring
as an argument type is not recommended (at least for now), andUnion[bytes, unicode]
is the recommended, hopefully future-proof alternative in Python 2 -- even though it's currently equivalent to justunicode
.Also say the
basestring
should not be used as a return value or attribute type, butUnion[bytes, unicode]
should also be avoided there. In these contextsstr
,bytes
,unicode
andAnyStr
are better, whenever possible.See also python/typeshed#202.
The text was updated successfully, but these errors were encountered: