accepting file path or file object?

Grant Edwards invalid at invalid.invalid
Mon Nov 5 16:05:23 CET 2012

On 2012-11-05, andrea crotti <andrea.crotti.0 at> wrote:

> Quite often I find convenient to get a filename or a file object as
> argument of a function, and do something as below:
> def grep_file(regexp, filepath_obj):
>     if isinstance(filepath_obj, basestring):
>         fobj = open(filepath_obj)
>     else:
>         fobj = filepath_obj
> This makes it also more convenient to unit-test, since I can just pass
> a StringIO.  But then there are other problems, for example if I pass
> a file object is the caller that has to make sure to close the file
> handle..
> So I'm thinking if it's not just worth to skip the support for file
> objects and only use the filenames, which seems a more robust and
> consistent choice..
> Any comment/suggestions about this?

I have found that accepting either a "file-like-object" or a filename
is sometimes worth the effort for a module that's going to be re-used
in a variety of contexts.  However, when I do it, I don't usually
check the type of the object -- I check for whatever "feature" I want
to use.  If I'm going to want to be able to call a read() method, I
check for presence of a read() method.  If that fails, then I assume
it's a filename and pass it to open().  If that fails, then it fails.

Grant Edwards               grant.b.edwards        Yow! Oh my GOD -- the
                                  at               SUN just fell into YANKEE

More information about the Python-list mailing list