【发布时间】:2017-11-27 19:47:47
【问题描述】:
是否有兼容 Python 2/3 的方法来检查对象是否为文件?
我需要检查对象 filehandler 是否实际上是 file 对象。这段代码需要在 Python 2 和 3 中运行。在 Python 2 中我可以做到
isinstance(filehandler, file)
但是file is not part of Python 3,所以这段代码在使用 Python 3 运行时会引发 NameError。
根据this answer,在Python 3 中io.IOBase 应该用于检查对象是否为文件,但Python 2 的file 没有子类io.IOBase,因此isinstance(filehandler, io.IOBase) 将不起作用。
我考虑过使用isinstance(filehandler, (io.IOBase, file)),但是当我使用 Python 3 运行它时,它仍然给出了NameError。
有没有一种方法可以同时兼容 Python 2.7 和 3?
【问题讨论】:
标签: python python-3.x python-2.7 compatibility