Reputation: 8563
I'm porting from Python 2.7 to Python 3.3.2. In Python 2.7, I used to be able to do something like assert(type(something) == file)
, but it seems that in Python 3.3.2 this is wrong. How do I do a similar thing in Python 3.3.2?
Upvotes: 15
Views: 17355
Reputation: 1121416
Python 3 file objects are part of the io
module, test against ABC classes in that module:
from io import IOBase
if isinstance(someobj, IOBase):
Don't use type(obj) == file
in Python 2; you'd use isinstance(obj, file)
instead. Even then, you would want to test for the capabilities; something the io
ABCs let you do; the isinstance()
function will return True
for any object that implements all the methods the Abstract Base Class defines.
Demo:
>>> from io import IOBase
>>> fh = open('/tmp/demo', 'w')
>>> isinstance(fh, IOBase)
True
>>> isinstance(object(), IOBase)
False
Upvotes: 28