Show More
@@ -1,48 +1,50 b'' | |||
|
1 | 1 | """Backwards compatibility - we use contextlib.nested to support Python 2.6, |
|
2 | 2 | but it's removed in Python 3.2.""" |
|
3 | 3 | |
|
4 | 4 | # TODO : Remove this once we drop support for Python 2.6, and use |
|
5 | 5 | # "with a, b:" instead. |
|
6 | 6 | |
|
7 | import sys | |
|
8 | ||
|
7 | 9 | from contextlib import contextmanager |
|
8 | 10 | |
|
9 | 11 | @contextmanager |
|
10 | 12 | def nested(*managers): |
|
11 | 13 | """Combine multiple context managers into a single nested context manager. |
|
12 | 14 | |
|
13 | 15 | This function has been deprecated in favour of the multiple manager form |
|
14 | 16 | of the with statement. |
|
15 | 17 | |
|
16 | 18 | The one advantage of this function over the multiple manager form of the |
|
17 | 19 | with statement is that argument unpacking allows it to be |
|
18 | 20 | used with a variable number of context managers as follows: |
|
19 | 21 | |
|
20 | 22 | with nested(*managers): |
|
21 | 23 | do_something() |
|
22 | 24 | |
|
23 | 25 | """ |
|
24 | 26 | exits = [] |
|
25 | 27 | vars = [] |
|
26 | 28 | exc = (None, None, None) |
|
27 | 29 | try: |
|
28 | 30 | for mgr in managers: |
|
29 | 31 | exit = mgr.__exit__ |
|
30 | 32 | enter = mgr.__enter__ |
|
31 | 33 | vars.append(enter()) |
|
32 | 34 | exits.append(exit) |
|
33 | 35 | yield vars |
|
34 | 36 | except: |
|
35 | 37 | exc = sys.exc_info() |
|
36 | 38 | finally: |
|
37 | 39 | while exits: |
|
38 | 40 | exit = exits.pop() |
|
39 | 41 | try: |
|
40 | 42 | if exit(*exc): |
|
41 | 43 | exc = (None, None, None) |
|
42 | 44 | except: |
|
43 | 45 | exc = sys.exc_info() |
|
44 | 46 | if exc != (None, None, None): |
|
45 | 47 | # Don't rely on sys.exc_info() still containing |
|
46 | 48 | # the right information. Another exception may |
|
47 | 49 | # have been raised and caught by an exit method |
|
48 | 50 | raise exc[0], exc[1], exc[2] |
General Comments 0
You need to be logged in to leave comments.
Login now