Check if variable is an instance of a File object

George Sakkis george.sakkis at gmail.com
Fri Sep 15 15:40:37 EDT 2006


Bruno Desthuilliers wrote:

> sc_wizard29 at hotmail.com wrote:
> > #1 : should I start by checking that 'file' is indeed an instance of a
> > File object ?
>
> Unless you have a *very* compelling reason to do so (and I can't imagine
>  one here), definitively, no. FWIW, it's pretty common in Python to pass
> file-like objects (StringIo comes to mind... but there are lots of other
> cases) to functions expecting a file object. And remember that Python
> doesn't relies on inheritence for typing. Also, for what you showed of
> your code, any iterable seems ok !-)

Well, not quite; string comes to mind as a common counter example.
Still, a usually better way to handle a string argument than raising an
exception is wrap it in StringIO:

from cStringIO import StringIO

def show_lines(text):
    if isinstance(text,basestring):
        text = StringIO(text)
   for line in text:
       # do something

	   
George




More information about the Python-list mailing list