Re: accepting file path or file object?

Discussion in 'Python' started by Cameron Simpson, Nov 5, 2012.

  1. On 05Nov2012 10:54, 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:

    I tend to do this:

    def f(fp):
    if isinstance(fp, str):
    with open(fp) as subfp:
    return f(subfp)
    ... main code using fp as file object ...

    That solves the file close issue neatly and lets you put this stuff up
    the top where it is obvious.

    | 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..

    You can't always use filenames; plenty of calling code will already have
    a file-like object to hand (eg a HTTP response or a StringIO or an
    already opened file or any of a million other things). So requiring
    filenames all the time is unreasonable.

    It is almost always etter to write for file objects, since that is what
    you would be converting any passed filename into, and put a self call at
    the top to convert a filename into a file object if that is a reasonable
    use case in your app.

    Cheers,
    --
    Cameron Simpson <>

    ....valve spreeengs? VALVE _*SPREEEEEEEEENGS*_!?! We don' neeeed
    no steeeenking valve spreeeeeengs!... - Dr. Desmo
     
    Cameron Simpson, Nov 5, 2012
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Stephen Ferg
    Replies:
    30
    Views:
    948
    Andrew Dalke
    Sep 30, 2003
  2. andrea crotti

    accepting file path or file object?

    andrea crotti, Nov 5, 2012, in forum: Python
    Replies:
    2
    Views:
    274
    Grant Edwards
    Nov 5, 2012
  3. Peter Otten

    Re: accepting file path or file object?

    Peter Otten, Nov 5, 2012, in forum: Python
    Replies:
    0
    Views:
    231
    Peter Otten
    Nov 5, 2012
  4. Peter Otten

    Re: accepting file path or file object?

    Peter Otten, Nov 5, 2012, in forum: Python
    Replies:
    0
    Views:
    261
    Peter Otten
    Nov 5, 2012
  5. Terry Reedy

    Re: accepting file path or file object?

    Terry Reedy, Nov 5, 2012, in forum: Python
    Replies:
    0
    Views:
    213
    Terry Reedy
    Nov 5, 2012
Loading...

Share This Page