blob: 647efdd26de532d0b3469eefe6f60b9ee3c3326b [file] [log] [blame]
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001"""Utilities for with-statement contexts. See PEP 343."""
2
3import sys
Christian Heimes81ee3ef2008-05-04 22:42:01 +00004from functools import wraps
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00005
6__all__ = ["contextmanager", "nested", "closing"]
7
8class GeneratorContextManager(object):
9 """Helper for @contextmanager decorator."""
10
11 def __init__(self, gen):
12 self.gen = gen
13
Guido van Rossum1a5e21e2006-02-28 21:57:43 +000014 def __enter__(self):
15 try:
Georg Brandla18af4e2007-04-21 15:47:16 +000016 return next(self.gen)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +000017 except StopIteration:
18 raise RuntimeError("generator didn't yield")
19
20 def __exit__(self, type, value, traceback):
21 if type is None:
22 try:
Georg Brandla18af4e2007-04-21 15:47:16 +000023 next(self.gen)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +000024 except StopIteration:
25 return
26 else:
27 raise RuntimeError("generator didn't stop")
28 else:
Guido van Rossum2cc30da2007-11-02 23:46:40 +000029 if value is None:
30 # Need to force instantiation so we can reliably
31 # tell if we get the same exception back
32 value = type()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +000033 try:
34 self.gen.throw(type, value, traceback)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000035 raise RuntimeError("generator didn't stop after throw()")
Guido van Rossumb940e112007-01-10 16:19:56 +000036 except StopIteration as exc:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000037 # Suppress the exception *unless* it's the same exception that
38 # was passed to throw(). This prevents a StopIteration
39 # raised inside the "with" statement from being suppressed
40 return exc is not value
41 except:
42 # only re-raise if it's *not* the exception that was
43 # passed to throw(), because __exit__() must not raise
44 # an exception unless __exit__() itself failed. But throw()
45 # has to raise the exception to signal propagation, so this
46 # fixes the impedance mismatch between the throw() protocol
47 # and the __exit__() protocol.
48 #
49 if sys.exc_info()[1] is not value:
50 raise
Guido van Rossum1a5e21e2006-02-28 21:57:43 +000051
52
53def contextmanager(func):
54 """@contextmanager decorator.
55
56 Typical usage:
57
58 @contextmanager
59 def some_generator(<arguments>):
60 <setup>
61 try:
62 yield <value>
63 finally:
64 <cleanup>
65
66 This makes this:
67
68 with some_generator(<arguments>) as <variable>:
69 <body>
70
71 equivalent to this:
72
73 <setup>
74 try:
75 <variable> = <value>
76 <body>
77 finally:
78 <cleanup>
79
80 """
Christian Heimes81ee3ef2008-05-04 22:42:01 +000081 @wraps(func)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +000082 def helper(*args, **kwds):
83 return GeneratorContextManager(func(*args, **kwds))
Guido van Rossum1a5e21e2006-02-28 21:57:43 +000084 return helper
85
86
87@contextmanager
Thomas Wouters477c8d52006-05-27 19:21:47 +000088def nested(*managers):
Guido van Rossum1a5e21e2006-02-28 21:57:43 +000089 """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:
Guido van Rossum04110fb2007-08-24 16:32:05 +0000108 for mgr in managers:
109 exit = mgr.__exit__
110 enter = mgr.__enter__
111 vars.append(enter())
112 exits.append(exit)
113 yield vars
114 except:
115 exc = sys.exc_info()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000116 finally:
117 while exits:
118 exit = exits.pop()
119 try:
Guido van Rossumf6694362006-03-10 02:28:35 +0000120 if exit(*exc):
121 exc = (None, None, None)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000122 except:
123 exc = sys.exc_info()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000124 if exc != (None, None, None):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000125 # Don't rely on sys.exc_info() still containing
126 # the right information. Another exception may
127 # have been raised and caught by an exit method
Collin Winterc59dacd2007-09-01 20:27:58 +0000128 # exc[1] already has the __traceback__ attribute populated
129 raise exc[1]
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000130
131
Thomas Wouters477c8d52006-05-27 19:21:47 +0000132class closing(object):
133 """Context to automatically close something at the end of a block.
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000134
135 Code like this:
136
137 with closing(<module>.open(<arguments>)) as f:
138 <block>
139
140 is equivalent to this:
141
142 f = <module>.open(<arguments>)
143 try:
144 <block>
145 finally:
146 f.close()
147
148 """
Thomas Wouters477c8d52006-05-27 19:21:47 +0000149 def __init__(self, thing):
150 self.thing = thing
151 def __enter__(self):
152 return self.thing
153 def __exit__(self, *exc_info):
154 self.thing.close()