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 |
Raymond Hettinger | 91e3b9d | 2009-05-28 22:20:03 +0000 | [diff] [blame] | 5 | from warnings import warn |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 6 | |
| 7 | __all__ = ["contextmanager", "nested", "closing"] |
| 8 | |
| 9 | class GeneratorContextManager(object): |
| 10 | """Helper for @contextmanager decorator.""" |
| 11 | |
| 12 | def __init__(self, gen): |
| 13 | self.gen = gen |
| 14 | |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 15 | def __enter__(self): |
| 16 | try: |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 17 | return next(self.gen) |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 18 | except StopIteration: |
| 19 | raise RuntimeError("generator didn't yield") |
| 20 | |
| 21 | def __exit__(self, type, value, traceback): |
| 22 | if type is None: |
| 23 | try: |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 24 | next(self.gen) |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 25 | except StopIteration: |
| 26 | return |
| 27 | else: |
| 28 | raise RuntimeError("generator didn't stop") |
| 29 | else: |
Guido van Rossum | 2cc30da | 2007-11-02 23:46:40 +0000 | [diff] [blame] | 30 | if value is None: |
| 31 | # Need to force instantiation so we can reliably |
| 32 | # tell if we get the same exception back |
| 33 | value = type() |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 34 | try: |
| 35 | self.gen.throw(type, value, traceback) |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 36 | raise RuntimeError("generator didn't stop after throw()") |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 37 | except StopIteration as exc: |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 38 | # Suppress the exception *unless* it's the same exception that |
| 39 | # was passed to throw(). This prevents a StopIteration |
| 40 | # raised inside the "with" statement from being suppressed |
| 41 | return exc is not value |
| 42 | except: |
| 43 | # only re-raise if it's *not* the exception that was |
| 44 | # passed to throw(), because __exit__() must not raise |
| 45 | # an exception unless __exit__() itself failed. But throw() |
| 46 | # has to raise the exception to signal propagation, so this |
| 47 | # fixes the impedance mismatch between the throw() protocol |
| 48 | # and the __exit__() protocol. |
| 49 | # |
| 50 | if sys.exc_info()[1] is not value: |
| 51 | raise |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 52 | |
| 53 | |
| 54 | def contextmanager(func): |
| 55 | """@contextmanager decorator. |
| 56 | |
| 57 | Typical usage: |
| 58 | |
| 59 | @contextmanager |
| 60 | def some_generator(<arguments>): |
| 61 | <setup> |
| 62 | try: |
| 63 | yield <value> |
| 64 | finally: |
| 65 | <cleanup> |
| 66 | |
| 67 | This makes this: |
| 68 | |
| 69 | with some_generator(<arguments>) as <variable>: |
| 70 | <body> |
| 71 | |
| 72 | equivalent to this: |
| 73 | |
| 74 | <setup> |
| 75 | try: |
| 76 | <variable> = <value> |
| 77 | <body> |
| 78 | finally: |
| 79 | <cleanup> |
| 80 | |
| 81 | """ |
Christian Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 82 | @wraps(func) |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 83 | def helper(*args, **kwds): |
| 84 | return GeneratorContextManager(func(*args, **kwds)) |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 85 | return helper |
| 86 | |
| 87 | |
| 88 | @contextmanager |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 89 | def nested(*managers): |
Nick Coghlan | b7706b5 | 2009-06-23 10:55:52 +0000 | [diff] [blame] | 90 | """Combine multiple context managers into a single nested context manager. |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 91 | |
Nick Coghlan | b7706b5 | 2009-06-23 10:55:52 +0000 | [diff] [blame] | 92 | This function has been deprecated in favour of the multiple manager form |
| 93 | of the with statement. |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 94 | |
Nick Coghlan | b7706b5 | 2009-06-23 10:55:52 +0000 | [diff] [blame] | 95 | The one advantage of this function over the multiple manager form of the |
| 96 | with statement is that argument unpacking allows it to be |
| 97 | used with a variable number of context managers as follows: |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 98 | |
Nick Coghlan | b7706b5 | 2009-06-23 10:55:52 +0000 | [diff] [blame] | 99 | with nested(*managers): |
| 100 | do_something() |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 101 | |
| 102 | """ |
Raymond Hettinger | 91e3b9d | 2009-05-28 22:20:03 +0000 | [diff] [blame] | 103 | warn("With-statements now directly support multiple context managers", |
Raymond Hettinger | fde29be | 2009-06-10 16:13:42 +0000 | [diff] [blame] | 104 | DeprecationWarning, 3) |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 105 | exits = [] |
| 106 | vars = [] |
Guido van Rossum | f669436 | 2006-03-10 02:28:35 +0000 | [diff] [blame] | 107 | exc = (None, None, None) |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 108 | try: |
Guido van Rossum | 04110fb | 2007-08-24 16:32:05 +0000 | [diff] [blame] | 109 | for mgr in managers: |
| 110 | exit = mgr.__exit__ |
| 111 | enter = mgr.__enter__ |
| 112 | vars.append(enter()) |
| 113 | exits.append(exit) |
| 114 | yield vars |
| 115 | except: |
| 116 | exc = sys.exc_info() |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 117 | finally: |
| 118 | while exits: |
| 119 | exit = exits.pop() |
| 120 | try: |
Guido van Rossum | f669436 | 2006-03-10 02:28:35 +0000 | [diff] [blame] | 121 | if exit(*exc): |
| 122 | exc = (None, None, None) |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 123 | except: |
| 124 | exc = sys.exc_info() |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 125 | if exc != (None, None, None): |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 126 | # Don't rely on sys.exc_info() still containing |
| 127 | # the right information. Another exception may |
| 128 | # have been raised and caught by an exit method |
Collin Winter | c59dacd | 2007-09-01 20:27:58 +0000 | [diff] [blame] | 129 | # exc[1] already has the __traceback__ attribute populated |
| 130 | raise exc[1] |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 131 | |
| 132 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 133 | class closing(object): |
| 134 | """Context to automatically close something at the end of a block. |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 135 | |
| 136 | Code like this: |
| 137 | |
| 138 | with closing(<module>.open(<arguments>)) as f: |
| 139 | <block> |
| 140 | |
| 141 | is equivalent to this: |
| 142 | |
| 143 | f = <module>.open(<arguments>) |
| 144 | try: |
| 145 | <block> |
| 146 | finally: |
| 147 | f.close() |
| 148 | |
| 149 | """ |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 150 | def __init__(self, thing): |
| 151 | self.thing = thing |
| 152 | def __enter__(self): |
| 153 | return self.thing |
| 154 | def __exit__(self, *exc_info): |
| 155 | self.thing.close() |