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 |
Georg Brandl | 655fc70 | 2008-04-30 21:08:42 +0000 | [diff] [blame] | 4 | from functools import wraps |
Raymond Hettinger | 822b87f | 2009-05-29 01:46:48 +0000 | [diff] [blame] | 5 | from warnings import warn |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 6 | |
Nick Coghlan | afd5e63 | 2006-05-03 13:02:47 +0000 | [diff] [blame] | 7 | __all__ = ["contextmanager", "nested", "closing"] |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 8 | |
Nick Coghlan | afd5e63 | 2006-05-03 13:02:47 +0000 | [diff] [blame] | 9 | class GeneratorContextManager(object): |
| 10 | """Helper for @contextmanager decorator.""" |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 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: |
| 17 | return self.gen.next() |
| 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: |
| 24 | self.gen.next() |
| 25 | except StopIteration: |
| 26 | return |
| 27 | else: |
| 28 | raise RuntimeError("generator didn't stop") |
| 29 | else: |
Nick Coghlan | 3814a91 | 2007-11-02 10:09:12 +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) |
Phillip J. Eby | 6edd258 | 2006-03-25 00:28:24 +0000 | [diff] [blame] | 36 | raise RuntimeError("generator didn't stop after throw()") |
Phillip J. Eby | 93149d9 | 2006-04-10 17:56:29 +0000 | [diff] [blame] | 37 | except StopIteration, exc: |
Phillip J. Eby | 9388020 | 2006-04-03 21:20:07 +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 |
Phillip J. Eby | 93149d9 | 2006-04-10 17:56:29 +0000 | [diff] [blame] | 41 | return exc is not value |
Phillip J. Eby | 6edd258 | 2006-03-25 00:28:24 +0000 | [diff] [blame] | 42 | except: |
Phillip J. Eby | ccc7bb4 | 2006-03-25 04:32:12 +0000 | [diff] [blame] | 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 | # |
Phillip J. Eby | 6edd258 | 2006-03-25 00:28:24 +0000 | [diff] [blame] | 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 | |
Nick Coghlan | afd5e63 | 2006-05-03 13:02:47 +0000 | [diff] [blame] | 54 | def contextmanager(func): |
| 55 | """@contextmanager decorator. |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 56 | |
| 57 | Typical usage: |
| 58 | |
Nick Coghlan | afd5e63 | 2006-05-03 13:02:47 +0000 | [diff] [blame] | 59 | @contextmanager |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 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 | """ |
Georg Brandl | 655fc70 | 2008-04-30 21:08:42 +0000 | [diff] [blame] | 82 | @wraps(func) |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 83 | def helper(*args, **kwds): |
Nick Coghlan | afd5e63 | 2006-05-03 13:02:47 +0000 | [diff] [blame] | 84 | return GeneratorContextManager(func(*args, **kwds)) |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 85 | return helper |
| 86 | |
| 87 | |
Nick Coghlan | afd5e63 | 2006-05-03 13:02:47 +0000 | [diff] [blame] | 88 | @contextmanager |
Guido van Rossum | da5b701 | 2006-05-02 19:47:52 +0000 | [diff] [blame] | 89 | def nested(*managers): |
Nick Coghlan | 0d8b4e3 | 2009-06-23 10:19:30 +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 | 0d8b4e3 | 2009-06-23 10:19:30 +0000 | [diff] [blame] | 92 | This function has been deprecated in favour of the multiple manager form |
Nick Coghlan | 3a1dbb0 | 2009-06-23 10:51:02 +0000 | [diff] [blame] | 93 | of the with statement. |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 94 | |
Nick Coghlan | 0d8b4e3 | 2009-06-23 10:19:30 +0000 | [diff] [blame] | 95 | The one advantage of this function over the multiple manager form of the |
Nick Coghlan | 3a1dbb0 | 2009-06-23 10:51:02 +0000 | [diff] [blame] | 96 | with statement is that argument unpacking allows it to be |
Nick Coghlan | 0d8b4e3 | 2009-06-23 10:19:30 +0000 | [diff] [blame] | 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 | 0d8b4e3 | 2009-06-23 10:19:30 +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 | 822b87f | 2009-05-29 01:46:48 +0000 | [diff] [blame] | 103 | warn("With-statements now directly support multiple context managers", |
Raymond Hettinger | 1917ad5 | 2009-06-10 16:15:02 +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: |
Georg Brandl | ac4018a | 2007-08-23 18:11:33 +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): |
Nick Coghlan | da2268f | 2006-04-24 04:37:15 +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 |
| 129 | raise exc[0], exc[1], exc[2] |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 130 | |
| 131 | |
Nick Coghlan | a7e820a | 2006-04-25 10:56:51 +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 | """ |
Nick Coghlan | a7e820a | 2006-04-25 10:56:51 +0000 | [diff] [blame] | 149 | def __init__(self, thing): |
| 150 | self.thing = thing |
Nick Coghlan | a7e820a | 2006-04-25 10:56:51 +0000 | [diff] [blame] | 151 | def __enter__(self): |
| 152 | return self.thing |
| 153 | def __exit__(self, *exc_info): |
| 154 | self.thing.close() |