isinstance 文件 python 2.7 和 3.5

2024-02-13

在 Python 2.7 中我得到以下结果:

>>> with open("README.md", "r") as fin:
...     print(isinstance(fin, file))
... 
True

在 python 3.5 中我得到:

>>> with open("README.md", "r") as fin:
...     print(isinstance(fin, file))
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
NameError: name 'file' is not defined

所以,好吧,我查看了 Python 文档,发现在 Python 3.5 中,文件的类型是io.IOBase(或某些子类)。引导我这样做:

>>> import io
>>> with open("README.md", "r") as fin:
...     print(isinstance(fin, io.IOBase))
... 
True

但是当我尝试使用 Python 2.7 时:

>>> import io
>>> with open("README.md", "r") as fin:
...     print(isinstance(fin, io.IOBase))
... 
False

所以此时我很困惑。看着文档 https://docs.python.org/2/library/io.html#io.IOBase,我觉得Python 2.7应该报告True.

显然我错过了一些基本的东西,也许是因为现在是美国东部时间下午 6:30,但我有两个相关的问题:

  1. 为什么Python会报错False for isinstance(fin, io.IOBase)?
  2. 有没有办法测试变量是否是一个在 Python 2.7 和 3.5 中都可以工作的打开文件?

从链接的文档中:

在 Python 2.x 下,这被提议作为内置文件对象的替代方案

所以它们在 python 2.x 中是不一样的。

至于第 2 部分,这适用于 python2 和 3,尽管不是世界上最漂亮的东西:

import io
try:
    file_types = (file, io.IOBase)

except NameError:
    file_types = (io.IOBase,)

with open("README.md", "r") as fin:
    print(isinstance(fin, file_types))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

isinstance 文件 python 2.7 和 3.5 的相关文章

随机推荐