[Baypiggies] Conditional Context Managers

Jeremy Fishman jeremy.r.fishman at gmail.com
Tue Oct 27 20:21:27 CET 2009


Neat syntax!  Still doesn't account for the closing of a non-named file
argument, though.

This is uncanny timing, as I just ran into this issue today and came up with
this:

def foo(f_obj_or_name):
    if isinstance(f_obj_or_name, str):
        with open(f_obj_or_name) as f_obj:
            return foo(f_obj)

    [...] # do file processing

My problem actually involved both and input and output file... ugh, doubled
the above code

Cheers!
  - Jeremy


--
Jeremy R Fishman
jeremy.r.fishman at gmail.com
http://jfishman.org

On Tue, Oct 27, 2009 at 11:29 AM, Aahz <aahz at pythoncraft.com> wrote:

> On Tue, Oct 27, 2009, Andrew Dalke wrote:
> >
> > def process(file_obj_or_name):
> >     with isinstance(file_obj_or_name, str) and \
> >             open(file_obj_or_name) or file_obj_or_name as file_obj:
> >         print "First line", repr(file_obj.readline())
> >     sys.stdout.write("Finished with %r\n" % (file_obj_or_name,))
>
> Anyone using ``with`` ought to use the real ternary (reformatted to my
> preference ;-):
>
>     with (
>            open(file_obj_or_name)
>            if isinstance(file_obj_or_name, str)
>             else file_obj_or_name
>            ) as file_obj:
> --
> Aahz (aahz at pythoncraft.com)           <*>
> http://www.pythoncraft.com/
>
> "You could make Eskimos emigrate to the Sahara by vigorously arguing --
> at hundreds of screens' length -- for the wonder, beauty, and utility of
> snow."  --PNH to rb in r.a.sf.f
> _______________________________________________
> Baypiggies mailing list
> Baypiggies at python.org
> To change your subscription options or unsubscribe:
> http://mail.python.org/mailman/listinfo/baypiggies
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/baypiggies/attachments/20091027/0b025833/attachment.htm>


More information about the Baypiggies mailing list