[Python-Dev] PEP 343 - multiple context managers in one statement

Paul Moore p.f.moore at gmail.com
Tue Oct 25 22:40:30 CEST 2005


I have a deep suspicion that this has been done to death already, but
my searching ability isn't up to finding the reference. So I'll simply
ask the question, and not offer a long discussion:

Has the option of letting the with statement admit multiple context
managers been considered (and presumably rejected)?

I'm thinking of

    with expr1, expr2, expr3:
        # whatever

In some ways, this doesn't even need an extension to the PEP - giving
tuples suitable __enter__ and __exit__ methods would do it. Or, I
suppose a user-defined manager which combined a list of others:

    class combining:
        def __init__(*mgrs):
            self.mgrs = mgrs
        def __with__(self):
            return self
        def __enter__(self):
            return tuple(mgr.__enter__() for mgr in self.mgrs)
        def __exit__(self, type, value, tb):
            # first in, last out
            for mgr in reversed(self.mgrs):
                mgr.__exit__(type, value, tb)

Would that be worth using as an example in the PEP?

Sorry - it got a bit long anyway...

Paul.

PS The signature of __with__ in example 4 in the PEP is wrong - it has
an incorrect "lock" parameter.


More information about the Python-Dev mailing list