Author kristjan.jonsson
Recipients kristjan.jonsson, ncoghlan, r.david.murray
Date 2013-08-07.16:29:20
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <>
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 :)
Date User Action Args
2013-08-07 16:29:21kristjan.jonssonsetrecipients: + kristjan.jonsson, ncoghlan, r.david.murray
2013-08-07 16:29:21kristjan.jonssonsetmessageid: <>
2013-08-07 16:29:21kristjan.jonssonlinkissue18677 messages
2013-08-07 16:29:20kristjan.jonssoncreate