accepting file path or file object?

Terry Reedy tjreedy at
Mon Nov 5 19:30:17 CET 2012

On 11/5/2012 5:54 AM, andrea crotti 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):
>      """Check if the given text is found in any of the file lines, take
>      a path to a file or an opened file object
>      """
>      if isinstance(filepath_obj, basestring):
>          fobj = open(filepath_obj)
>      else:
>          fobj = filepath_obj
>      for line in fobj:
>          if, line):
>              return True
>      return False
> 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 [it] is the caller that has to make sure to close the file
> handle..

Which is as it should be. The caller should (normally) call your 
function within a with statement or might want to do other operations on 
the file before or after passing it to your grep_file.

Terry Jan Reedy

More information about the Python-list mailing list