python - 为什么 isinstance ('foo' , str) == False

标签 python string python-2.7

我使用 futurize 轻轻地将我的模块迁移到 Python3,现在我的文件顶部有以下内容:

from builtins import str

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

>>> isinstance('foo', (unicode, str))
False

如何正确解决这个问题?

请注意,添加 from __future__ import unicode_literals 没有帮助,因为 isinstance 是从其他地方调用的函数调用的,如果 unicode_literals 已正确导入。

编辑

我发现我可以使用这个:

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

这看起来非常样板......

最佳答案

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

isinstance('foo', six.string_types)

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

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

关于python - 为什么 isinstance ('foo' , str) == False,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40464421/

相关文章:

mysql - 使用 Python 在 MySQL 数据库上进行实时搜索

python - 防止 IOError : [Errno 4] Interrupted system call

python - tuple(aValidTupleOfTypeString) 没有返回我期望的结果

python - 重新连接期间的 getaddrinfo 行为

python - scipy.stats.multivariate_normal 提高 `LinAlgError: singular matrix` 即使我的协方差矩阵是可逆的

Jenkins 中的 Python 模块导入失败

string - 验证文本是否只有字母和空格

c++ - 从基数 11 到 10 c++ 的转换

php - 当output_buffering打开时回显多个参数

python - 带有 python-firebase 的 Firebase 抛出 "Connection reset by peer"(Celery + gevent 参与)