[Python-ideas] contextlib.maybe

Julian Berman julian at grayvines.com
Sun Dec 11 06:07:23 CET 2011


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)

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