StringType and NoneType in python3.x
I have a codebase which uses StringType and NoneType(types module) in the python2.x codebase. On porting to Python3, tests failed as the types module in Python3.x does not have the above mentioned two types.
I solved the problem by replacing them with "str" and "None" respectively. I was wondering if there is another (right)way of doing this. What I'm doing currently definitely seems to work, but I'm doubtful.
Should I stick to the approach I have followed or is there something wrong in what I have done? If so, how do I correc开发者_StackOverflow中文版t it?
Checking None is usually done by calling obj is None
, while checking for string usually is isinstance(obj, str)
. In Python 2.x to detect both string and unicode, you could use isinstance(obj, basestring)
.
If you use 2to3
, it's enough, but if you need to have single piece of code working in both Py2 and Py3, you may end up with something like that:
try:
return isinstance(obj, basestring)
except NameError:
return isinstance(obj, str)
Where possible I would recommend that you avoid the values in types
if their values are obvious; so for something like binding a method to an object, use types.MethodType
, but for types.StringTypes
use (str, unicode)
or rather basestring
.
For this situation, I would do this:
- Use
obj is None
orobj is not None
rather thanisinstance(obj, NoneType)
ornot isinstance(obj, NoneType)
. - Use
isinstance(obj, basestring)
rather thanisinstance(obj, StringTypes)
- Use
isinstance(obj, str)
rather thanisinstance(obj, StringType)
Then, when you're needing to distribute for Python 3, use 2to3
. Then your basestring
will become str
and the rest will continue to work as it did before.
(Also, bear in mind this, in particular the difference between StringType
and StringTypes
:
types.UnicodeType == unicode
types.StringType == str
types.StringTypes == (str, unicode)
)
精彩评论