python - How do you check if an object is an instance of 'file'? -


it used in python (2.6) 1 ask:

isinstance(f, file) 

but in python 3.0 file removed.

what proper method checking see if variable file now? what'snew docs don't mention this...

def read_a_file(f)     try:         contents = f.read()     except attributeerror:         # f not file 

substitute whatever methods plan use read. optimal if expect passed file object more 98% of time. if expect passed non file object more 2% of time, correct thing is:

def read_a_file(f):     if hasattr(f, 'read'):         contents = f.read()     else:         # f not file 

this if did have access file class test against. (and fwiw, have file on 2.6) note code works in 3.x well.


Comments

Popular posts from this blog

c++ - Convert big endian to little endian when reading from a binary file -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

unicode - Are email addresses allowed to contain non-alphanumeric characters? -