It used to be in Python (2.6) that one could ask:
isinstance(f, file)
but now "file" is undefined (using Python 3.0)
What is the proper method for checking to see if a variable is a file now? The What'sNew docs didn't mention this...
It used to be in Python (2.6) that one could ask:
isinstance(f, file)
but now "file" is undefined (using Python 3.0)
What is the proper method for checking to see if a variable is a file now? The What'sNew docs didn't mention this...
def read_a_file(f)
try:
contents = f.read()
except AttributeError:
# f is not a file
substitute whatever methods you plan to use for read
. This is optimal if you expect that you will get passed a file like object more than 98% of the time. If you expect that you will be passed a non file like object more often than 2% of the time, then the correct thing to do is:
def read_a_file(f):
if hasattr(f, 'read'):
contents = f.read()
else:
# f is not a file
This is exactly what you would do if you did have access to a file
class to test against. (and FWIW, I too have file
on 2.6) Note that this code works in 3.x as well.
Works for me on python 2.6... Are you in a strange environment where builtins aren't imported by default, or where somebody has done del file
, or something?
I just checked this out on my Python 2.6:
>>> f = open('filepath', 'r'):
>>> type(f) == file
True
Hope that solves your problem