[Baypiggies] Conditional Context Managers

Aahz aahz at pythoncraft.com
Tue Oct 27 19:29:32 CET 2009

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

More information about the Baypiggies mailing list