Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 1 | """Utilities for with-statement contexts. See PEP 343.""" |
| 2 | |
| 3 | import sys |
Christian Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 4 | from functools import wraps |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 5 | |
| 6 | __all__ = ["contextmanager", "nested", "closing"] |
| 7 | |
| 8 | class GeneratorContextManager(object): |
| 9 | """Helper for @contextmanager decorator.""" |
| 10 | |
| 11 | def __init__(self, gen): |
| 12 | self.gen = gen |
| 13 | |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 14 | def __enter__(self): |
| 15 | try: |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 16 | return next(self.gen) |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 17 | 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 Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 23 | next(self.gen) |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 24 | except StopIteration: |
| 25 | return |
| 26 | else: |
| 27 | raise RuntimeError("generator didn't stop") |
| 28 | else: |
Guido van Rossum | 2cc30da | 2007-11-02 23:46:40 +0000 | [diff] [blame] | 29 | 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 Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 33 | try: |
| 34 | self.gen.throw(type, value, traceback) |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 35 | raise RuntimeError("generator didn't stop after throw()") |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 36 | except StopIteration as exc: |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 37 | # 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 Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 51 | |
| 52 | |
| 53 | def 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 Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 81 | @wraps(func) |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 82 | def helper(*args, **kwds): |
| 83 | return GeneratorContextManager(func(*args, **kwds)) |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 84 | return helper |
| 85 | |
| 86 | |
| 87 | @contextmanager |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 88 | def nested(*managers): |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 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 Rossum | f669436 | 2006-03-10 02:28:35 +0000 | [diff] [blame] | 106 | exc = (None, None, None) |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 107 | try: |
Guido van Rossum | 04110fb | 2007-08-24 16:32:05 +0000 | [diff] [blame] | 108 | 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 Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 116 | finally: |
| 117 | while exits: |
| 118 | exit = exits.pop() |
| 119 | try: |
Guido van Rossum | f669436 | 2006-03-10 02:28:35 +0000 | [diff] [blame] | 120 | if exit(*exc): |
| 121 | exc = (None, None, None) |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 122 | except: |
| 123 | exc = sys.exc_info() |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 124 | if exc != (None, None, None): |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 125 | # 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 Winter | c59dacd | 2007-09-01 20:27:58 +0000 | [diff] [blame] | 128 | # exc[1] already has the __traceback__ attribute populated |
| 129 | raise exc[1] |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 130 | |
| 131 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 132 | class closing(object): |
| 133 | """Context to automatically close something at the end of a block. |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 134 | |
| 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 Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 149 | 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() |