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

ruby - When to use an ORM (Sequel, Datamapper, AR, etc.) vs. pure SQL for querying -

php - PHPDoc: @return void necessary? -

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