python3.x中的StringType和NoneType

2024-06-16 14:57:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个代码库,在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?


Tags: 模块to方法代码none类型havepython3
2条回答

检查None通常通过调用obj is None来完成,而检查string通常是isinstance(obj, str)。在Python2.x中,要同时检测字符串和unicode,可以使用isinstance(obj, basestring)

如果您使用2to3,这就足够了,但是如果您需要在Py2和Py3中同时使用一段代码,您可能会得到这样的结果:

try:
    return isinstance(obj, basestring)
except NameError:
    return isinstance(obj, str)

如果types中的值是明显的,我建议您尽可能避免使用这些值;因此对于将方法绑定到对象之类的内容,请使用types.MethodType,而对于types.StringTypes则使用(str, unicode)basestring

在这种情况下,我会这样做:

  • 使用obj is Noneobj 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,剩下的将继续像以前那样工作。

(还要记住,特别是StringTypeStringTypes之间的区别:

types.UnicodeType == unicode
types.StringType == str
types.StringTypes == (str, unicode)

(第页)

相关问题 更多 >