[Python-ideas] ExitStack: Allow exiting individual context managers

Michael Selik mike at selik.org
Mon Dec 7 22:52:42 EST 2015


On Mon, Dec 7, 2015 at 3:37 PM Ram Rachum <ram at rachum.com> wrote:

> I can't use a with statement, because there's a condition around the place
> where I acquire the lock. It's something like this:
>
> if condition:
>
>     exit_stack.enter_context(get_lock_1())
>
> else:
>
>     exit_stack.enter_context(get_lock_2())
>
>
You can't put the condition in a context manager's __init__ or __enter__?

    class CM:
        def __init__(self, condition):
            self.lock = lock1 if condition else lock2
        def __enter__(self):
            self.lock.acquire()
        delf __exit__(self, *info):
            self.lock.release()
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20151208/8426a7c8/attachment.html>


More information about the Python-ideas mailing list