Check if variable is an instance of a File object

Peter Otten __peter__ at web.de
Fri Sep 15 04:12:32 EDT 2006


sc_wizard29 at hotmail.com wrote:

> 
> Marc 'BlackJack' Rintsch a ecrit :
> 
>> And what do you do if you check for `file` and it isn't such an instance?
>> Raise an exception?  A no, that's something you don't like.  So what
>> else?  ;-)
> 
> Well, I prefer the idea of raising my *own* exception to the idea of
> having an unknown behavior occur (for ex : what if the argument is NOT
> a File, but is "itereable" ?)
> 
> But anyway, I guess the most "pythonic" way is to do nothing ;-)

Indeed, don't waste time to make your code less general. Why would you want
to prevent your show_lines() function from processing a list of strings or
a StringIO?
 
> One more question : how to test if 'file' is a File object ?

The file type is actually spelt lowercase, so 'file' is not a good idea as a
variable name.

>>> f = file("tmp.txt")
>>> isinstance(f, file) # isinstance(f, open) looks odd
True

isinstance() returns True for subclasses, if you don't want that either:

>>> type(f) is file
True

Peter



More information about the Python-list mailing list