Ship with our own version of contexlib.nested

This commit is contained in:
Ask Solem 2011-09-09 14:56:11 +01:00
parent 2f6fe164e8
commit 70ef1e74f5
2 changed files with 36 additions and 4 deletions

View File

@ -3,14 +3,14 @@ from __future__ import with_statement
import socket
from contextlib import nested, contextmanager
from contextlib import contextmanager
from functools import partial
from itertools import count
from kombu.messaging import Consumer
from .messaging import Consumer
from kombu.utils import cached_property
from kombu.utils.limits import TokenBucket
from .utils import cached_property, nested
from .utils.limits import TokenBucket
__all__ = ["ConsumerMixin"]

View File

@ -2,6 +2,7 @@ from __future__ import absolute_import
import sys
from contextlib import contextmanager
from time import sleep
from uuid import UUID, uuid4 as _uuid4, _uuid_generate_random
@ -224,3 +225,34 @@ def reprcall(name, args=(), kwargs=(), sep=', '):
return "%s(%s%s%s)" % (name, sep.join(map(_safe_repr, args)),
(args and kwargs) and sep or "",
reprkwargs(kwargs, sep))
@contextmanager
def nested(*managers):
"""Combine multiple context managers into a single nested
context manager."""
exits = []
vars = []
exc = (None, None, None)
try:
for mgr in managers:
exit = mgr.__exit__
enter = mgr.__enter__
vars.append(enter())
exits.append(exit)
yield vars
except:
exc = sys.exc_info()
finally:
while exits:
exit = exits.pop()
try:
if exit(*exc):
exc = (None, None, None)
except:
exc = sys.exc_info()
if exc != (None, None, None):
# Don't rely on sys.exc_info() still containing
# the right information. Another exception may
# have been raised and caught by an exit method
raise exc[0], exc[1], exc[2]