blob: 9c00ef0777dab262d2560d5ee421157d25f34ce3 [file] [log] [blame]
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001"""Utilities for with-statement contexts. See PEP 343."""
2
3import sys
4
5__all__ = ["contextmanager", "nested", "closing"]
6
7class GeneratorContextManager(object):
8 """Helper for @contextmanager decorator."""
9
10 def __init__(self, gen):
11 self.gen = gen
12
13 def __context__(self):
14 return self
15
16 def __enter__(self):
17 try:
18 return self.gen.next()
19 except StopIteration:
20 raise RuntimeError("generator didn't yield")
21
22 def __exit__(self, type, value, traceback):
23 if type is None:
24 try:
25 self.gen.next()
26 except StopIteration:
27 return
28 else:
29 raise RuntimeError("generator didn't stop")
30 else:
31 try:
32 self.gen.throw(type, value, traceback)
Phillip J. Eby6edd2582006-03-25 00:28:24 +000033 raise RuntimeError("generator didn't stop after throw()")
Guido van Rossum1a5e21e2006-02-28 21:57:43 +000034 except StopIteration:
Guido van Rossumf6694362006-03-10 02:28:35 +000035 return True
Phillip J. Eby6edd2582006-03-25 00:28:24 +000036 except:
Phillip J. Ebyccc7bb42006-03-25 04:32:12 +000037 # only re-raise if it's *not* the exception that was
38 # passed to throw(), because __exit__() must not raise
39 # an exception unless __exit__() itself failed. But throw()
40 # has to raise the exception to signal propagation, so this
41 # fixes the impedance mismatch between the throw() protocol
42 # and the __exit__() protocol.
43 #
Phillip J. Eby6edd2582006-03-25 00:28:24 +000044 if sys.exc_info()[1] is not value:
45 raise
Guido van Rossum1a5e21e2006-02-28 21:57:43 +000046
47
48def contextmanager(func):
49 """@contextmanager decorator.
50
51 Typical usage:
52
53 @contextmanager
54 def some_generator(<arguments>):
55 <setup>
56 try:
57 yield <value>
58 finally:
59 <cleanup>
60
61 This makes this:
62
63 with some_generator(<arguments>) as <variable>:
64 <body>
65
66 equivalent to this:
67
68 <setup>
69 try:
70 <variable> = <value>
71 <body>
72 finally:
73 <cleanup>
74
75 """
76 def helper(*args, **kwds):
77 return GeneratorContextManager(func(*args, **kwds))
78 try:
79 helper.__name__ = func.__name__
80 helper.__doc__ = func.__doc__
Phillip J. Eby35fd1422006-03-28 00:07:24 +000081 helper.__dict__ = func.__dict__
Guido van Rossum1a5e21e2006-02-28 21:57:43 +000082 except:
83 pass
84 return helper
85
86
87@contextmanager
88def nested(*contexts):
89 """Support multiple context managers in a single with-statement.
90
91 Code like this:
92
93 with nested(A, B, C) as (X, Y, Z):
94 <body>
95
96 is equivalent to this:
97
98 with A as X:
99 with B as Y:
100 with C as Z:
101 <body>
102
103 """
104 exits = []
105 vars = []
Guido van Rossumf6694362006-03-10 02:28:35 +0000106 exc = (None, None, None)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000107 try:
108 try:
109 for context in contexts:
110 mgr = context.__context__()
111 exit = mgr.__exit__
112 enter = mgr.__enter__
113 vars.append(enter())
114 exits.append(exit)
115 yield vars
116 except:
117 exc = sys.exc_info()
118 finally:
119 while exits:
120 exit = exits.pop()
121 try:
Guido van Rossumf6694362006-03-10 02:28:35 +0000122 if exit(*exc):
123 exc = (None, None, None)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000124 except:
125 exc = sys.exc_info()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000126 if exc != (None, None, None):
127 raise
128
129
130@contextmanager
131def closing(thing):
132 """Context manager to automatically close something at the end of a block.
133
134 Code like this:
135
136 with closing(<module>.open(<arguments>)) as f:
137 <block>
138
139 is equivalent to this:
140
141 f = <module>.open(<arguments>)
142 try:
143 <block>
144 finally:
145 f.close()
146
147 """
148 try:
149 yield thing
150 finally:
151 thing.close()