[Python-ideas] contextlib.maybe
Mathias Panzenböck
grosser.meister.morti at gmx.net
Fri Dec 16 05:21:52 CET 2011
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.
> 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)
>
> where `maybe` takes an object and conditionally runs a context manager
> if a check fails. Implementation would be:
>
>
> @contextlib.contextmanager
> def maybe(got, contextfactory, *args, checkif=bool, **kwargs):
> if checkif(got):
> yield got
> else:
> with contextfactory(*args, **kwargs) as got:
> yield got
>
>
> It's hard to gauge utility for such simple functions (though contextlib
> already has closing(), so I figured it'd be worth asking at least).
> Would this be useful to others? Or perhaps I'm completely missing
> something and you've got suggestions on how to better have an API where
> an argument can be fetched if not provided but a context manager would
> preferably need to be run to do so.
More information about the Python-ideas
mailing list