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?
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.
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 .
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With