Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

isinstance file python 2.7 and 3.5

Tags:

python

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:

  1. Why does Python report False for isinstance(fin, io.IOBase)?
  2. Is there a way to test that a variable is an open file which will work in both Python 2.7 and 3.5?
like image 236
iLoveTux Avatar asked Mar 30 '16 22:03

iLoveTux


2 Answers

From the linked documentation:

Under Python 2.x, this is proposed as an alternative to the built-in file object

So they are not the same in python 2.x.

As to part 2, this works in python2 and 3, though not the prettiest thing in the world:

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))
like image 153
Ilja Everilä Avatar answered Nov 12 '22 06:11

Ilja Everilä


For python2

import types
f = open('test.txt', 'r')   # assuming this file exists
print (isinstance(f,types.FileType))

For python3

import io
import types
f1 = open('test.txt', 'r')   # assuming this file exists
f2 = open('test.txt', 'rb')   # assuming this file exists
print (isinstance(f1,io.IOBase))
print (isinstance(f2,io.IOBase))

(Edit: my previous solution tested for io.TextIOWrapper, it worked only with files opened in text mode. See https://docs.python.org/3/library/io.html#class-hierarchy which describes the python3 class hierarchy).

like image 45
Sci Prog Avatar answered Nov 12 '22 07:11

Sci Prog