[issue18677] Enhanced context managers with ContextManagerExit and None

Kristján Valur Jónsson report at bugs.python.org
Wed Aug 7 18:29:21 CEST 2013


Kristján Valur Jónsson added the comment:

Simply put, there is no way in the language to nest two context managers, even though we have full access to their implementation model, i.e. can call __enter__ and __exit__ manually.  This reflects badly (pun intended) on Python's reflection and introspection capabilities.

If context managers are to be first class entities in the language, then you ought to be able to write absract code using them, and
assemble complex ones out of simple ones.  Hypothetical code here:

def nest(a, b):
    # currently not possible
    return c

def run_with_context(ctxt, callable):
    # abstract executor
    with ctxt:
        return callable()

run_with_context(nested(a,b), callable)

ExitStack address one use case that contextlib.nested was supposed to solve, namely the cleanup of a dynamic sequence of context managers.  But it does this no by creating a new manager, but by providing a programming pattern to follow.  In that sensse, the multiple context manager syntax (with (a, b, c): ) is also a hack because it provides language magic to perform what you ought to be able to do dynamically...

Does this makes sense?

Anyway, by providing the ContextManagerExit exception, then sufficient flexibility is added to the context manager mechanism that at least the use case of nested() becomes possible.

Context managers are really interesting things.  I was inspired by Raymond Hettinger's talk last pycon to explore their capabilities and this is one of the things I came up with :)

----------

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue18677>
_______________________________________


More information about the Python-bugs-list mailing list