Python 3.3.2 verify that an object has a file type

I am migrating from Python 2.7 to Python 3.3.2. In Python 2.7, I used to do something like assert(type(something) == file) , but it seems like this is wrong in Python 3.3.2. How can I do this in Python 3.3.2?

+7
python types file
source share
1 answer

Python 3 file objects are part of the io module , check the ABC classes in this module:

 from io import IOBase if isinstance(someobj, IOBase): 

Do not use type(obj) == file in Python 2; you would use isinstance(obj, file) instead. Even then you will want to test the possibilities; what ABC io allows you to do; the isinstance() function returns True for any object that implements all the methods defined by the base class.

Demo:

 >>> from io import IOBase >>> fh = open('/tmp/demo', 'w') >>> isinstance(fh, IOBase) True >>> isinstance(object(), IOBase) False 
+16
source share

All Articles