[Python-ideas] contextlib.maybe
Terry Reedy
tjreedy at udel.edu
Sun Dec 11 07:02:30 CET 2011
On 12/11/2011 12:07 AM, Julian Berman wrote:
> Twice recently I've found myself wanting to write the following code:
>
> def fn(a_file=None):
> responsible_for_closing = False
>
> if a_file is None:
> a_file = open(a_default_location)
> responsible_for_closing = True
>
> do_stuff(a_file)
>
> if responsible_for_closing:
> a_file.close()
>
> which can be written slightly shorter I know, but it's still a tiny bit
> messy and repetitive. What I'd prefer to write is something more like:
>
> def fn(a_file=None):
> with contextlib.maybe(a_file, open, default) as a_file:
> do_stuff(a_file)
Expecting contextlib to have such a specialized context manager that
does exactly what you want is perhaps too much. However, you should be
able to write a class yourself that keeps the flag and does the
conditional opening and closing in the __enter__ and __exit__ methods.
--
Terry Jan Reedy
More information about the Python-ideas
mailing list