[Python-ideas] contextlib.maybe
Nick Coghlan
ncoghlan at gmail.com
Fri Dec 16 09:34:54 CET 2011
On Fri, Dec 16, 2011 at 2:21 PM, Mathias Panzenböck
<grosser.meister.morti at gmx.net> wrote:
> On 12/11/2011 06: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()
>>
>
> What about this?
>
> def fn(a_file=None):
> if a_file is None:
> with open(a_default_location) as a_file:
> do_stuff(a_file)
> else:
> do_stuff(a_file)
>
>
> That's how I do it when this comes up.
With contextlib2.ContextStack [1] the problem of conditional release
of resources can be handled as follows:
def fn(a_file=None):
with ContextStack() as stack:
if a_file is None:
# The stack will release the file when we're done
a_file = stack.enter_context(open(a_default_location))
do_stuff(a_file)
If you're interested in seeing this (or something like it) in the
standard library for 3.3, grab the module of PyPI, play around with it
and send me feedback on the BitBucket issue tracker [2].
[1] http://contextlib2.readthedocs.org/en/latest/index.html#contextlib2.ContextStack
[2] https://bitbucket.org/ncoghlan/contextlib2/issues?status=new&status=open
Cheers,
Nick.
--
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
More information about the Python-ideas
mailing list