我有一个代码库,在python2.x代码库中使用StringType和NoneType(types模块)。在移植到Python3时,测试失败,因为Python3.x中的types模块没有上述两种类型。
我分别用“str”和“None”替换它们,解决了这个问题。我想知道有没有别的(正确的)方法来做这件事。我现在所做的似乎确实有效,但我怀疑。
Should I stick to the approach I have followed or is there something wrong in what I have done? If so, how do I correct it?
检查None通常通过调用
obj is None
来完成,而检查string通常是isinstance(obj, str)
。在Python2.x中,要同时检测字符串和unicode,可以使用isinstance(obj, basestring)
。如果您使用
2to3
,这就足够了,但是如果您需要在Py2和Py3中同时使用一段代码,您可能会得到这样的结果:如果
types
中的值是明显的,我建议您尽可能避免使用这些值;因此对于将方法绑定到对象之类的内容,请使用types.MethodType
,而对于types.StringTypes
则使用(str, unicode)
或basestring
。在这种情况下,我会这样做:
obj is None
或obj is not None
,而不是isinstance(obj, NoneType)
或not isinstance(obj, NoneType)
。isinstance(obj, basestring)
而不是isinstance(obj, StringTypes)
isinstance(obj, str)
而不是isinstance(obj, StringType)
然后,当您需要为Python 3分发时,使用
2to3
。然后你的basestring
将变成str
,剩下的将继续像以前那样工作。(还要记住,特别是
StringType
和StringTypes
之间的区别:(第页)
相关问题 更多 >
编程相关推荐