为什么isinstance('foo',str)==Fals

2024-04-25 09:39:35 发布

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

我使用futurize轻轻地将我的模块迁移到Python3,现在我在文件的顶部有了这个:

from builtins import str

future.types.newstr.BaseNewStr导致我对isinstance的一个错误结果:

^{pr2}$

如何妥善解决这个问题?在

请注意,添加from __future__ import unicode_literals没有帮助,因为如果正确导入unicode_literals,那么isinstance是从我无法控制的其他地方调用的函数调用的。在

编辑

我发现我可以用这个:

def foo(string):
   import six
   if isinstance(string, six.string_types):
      return six.types.StringType('bar')

看起来很像样板。。。在


Tags: 模块文件fromimportstringunicodefuturepython3
1条回答
网友
1楼 · 发布于 2024-04-25 09:39:35

我不清楚您希望用样板代码实现什么,但是检查实例类型的正确方法是存在的。 要回答您的问题以修复isinstance检查,您只需

isinstance('foo', six.string_types)

是的,您还必须将six库导入到您想使用它的任何地方,这在处理python2/3代码时很常见。在

顺便说一句,如果您不需要python2兼容性,只想迁移到python3,那么就不需要从future(内置函数)导入

相关问题 更多 >