In Python 2.7 I get the following results:
>>> with open("README.md", "r") as fin:
... print(isinstance(fin, file))
...
True
In python 3.5 I get:
>>> 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
So, OK I look at the Python docs and find out that in Python 3.5, files are of type io.IOBase
(or some subclass). Leading me to this:
>>> import io
>>> with open("README.md", "r") as fin:
... print(isinstance(fin, io.IOBase))
...
True
But then when I try in Python 2.7:
>>> import io
>>> with open("README.md", "r") as fin:
... print(isinstance(fin, io.IOBase))
...
False
So at this point, I'm confused. Looking at the documentation, I feel as though Python 2.7 should report True
.
Obviously I'm missing something elementary, perhaps because it's 6:30 PM ET, but I have two related questions:
- Why does Python report
False
forisinstance(fin, io.IOBase)
? - Is there a way to test that a variable is an open file which will work in both Python 2.7 and 3.5?