Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3.3.2 check that object is of type file

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?

like image 752
Ray Avatar asked Sep 18 '13 19:09

Ray


People also ask

How do you check the type of an object in Python?

To get the type of a variable in Python, you can use the built-in type() function. In Python, everything is an object. So, when you use the type() function to print the type of the value stored in a variable to the console, it returns the class type of the object.

How do you check if a variable is an object in Python?

Using isinstance() function, we can test whether an object/variable is an instance of the specified type or class such as int or list. In the case of inheritance, we can checks if the specified class is the parent class of an object. For example, isinstance(x, int) to check if x is an instance of a class int .

Can Python read any file type?

There are two types of files that can be handled in python, normal text files and binary files (written in binary language, 0s, and 1s). Text files: In this type of file, Each line of text is terminated with a special character called EOL (End of Line), which is the new line character ('\n') in python by default.


1 Answers

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
like image 193
Martijn Pieters Avatar answered Sep 19 '22 15:09

Martijn Pieters