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 |
| 4 | |
Nick Coghlan | a7e820a | 2006-04-25 10:56:51 +0000 | [diff] [blame] | 5 | __all__ = ["contextfactory", "nested", "closing"] |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 6 | |
Nick Coghlan | a7e820a | 2006-04-25 10:56:51 +0000 | [diff] [blame] | 7 | class GeneratorContext(object): |
| 8 | """Helper for @contextfactory decorator.""" |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 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. Eby | 6edd258 | 2006-03-25 00:28:24 +0000 | [diff] [blame] | 33 | raise RuntimeError("generator didn't stop after throw()") |
Phillip J. Eby | 93149d9 | 2006-04-10 17:56:29 +0000 | [diff] [blame] | 34 | except StopIteration, exc: |
Phillip J. Eby | 9388020 | 2006-04-03 21:20:07 +0000 | [diff] [blame] | 35 | # Suppress the exception *unless* it's the same exception that |
| 36 | # was passed to throw(). This prevents a StopIteration |
| 37 | # raised inside the "with" statement from being suppressed |
Phillip J. Eby | 93149d9 | 2006-04-10 17:56:29 +0000 | [diff] [blame] | 38 | return exc is not value |
Phillip J. Eby | 6edd258 | 2006-03-25 00:28:24 +0000 | [diff] [blame] | 39 | except: |
Phillip J. Eby | ccc7bb4 | 2006-03-25 04:32:12 +0000 | [diff] [blame] | 40 | # only re-raise if it's *not* the exception that was |
| 41 | # passed to throw(), because __exit__() must not raise |
| 42 | # an exception unless __exit__() itself failed. But throw() |
| 43 | # has to raise the exception to signal propagation, so this |
| 44 | # fixes the impedance mismatch between the throw() protocol |
| 45 | # and the __exit__() protocol. |
| 46 | # |
Phillip J. Eby | 6edd258 | 2006-03-25 00:28:24 +0000 | [diff] [blame] | 47 | if sys.exc_info()[1] is not value: |
| 48 | raise |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 49 | |
| 50 | |
Nick Coghlan | a7e820a | 2006-04-25 10:56:51 +0000 | [diff] [blame] | 51 | def contextfactory(func): |
| 52 | """@contextfactory decorator. |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 53 | |
| 54 | Typical usage: |
| 55 | |
Brett Cannon | 1e01397 | 2006-04-29 21:29:50 +0000 | [diff] [blame^] | 56 | @contextfactory |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 57 | def some_generator(<arguments>): |
| 58 | <setup> |
| 59 | try: |
| 60 | yield <value> |
| 61 | finally: |
| 62 | <cleanup> |
| 63 | |
| 64 | This makes this: |
| 65 | |
| 66 | with some_generator(<arguments>) as <variable>: |
| 67 | <body> |
| 68 | |
| 69 | equivalent to this: |
| 70 | |
| 71 | <setup> |
| 72 | try: |
| 73 | <variable> = <value> |
| 74 | <body> |
| 75 | finally: |
| 76 | <cleanup> |
| 77 | |
| 78 | """ |
| 79 | def helper(*args, **kwds): |
Nick Coghlan | a7e820a | 2006-04-25 10:56:51 +0000 | [diff] [blame] | 80 | return GeneratorContext(func(*args, **kwds)) |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 81 | try: |
| 82 | helper.__name__ = func.__name__ |
| 83 | helper.__doc__ = func.__doc__ |
Phillip J. Eby | 35fd142 | 2006-03-28 00:07:24 +0000 | [diff] [blame] | 84 | helper.__dict__ = func.__dict__ |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 85 | except: |
| 86 | pass |
| 87 | return helper |
| 88 | |
| 89 | |
Nick Coghlan | a7e820a | 2006-04-25 10:56:51 +0000 | [diff] [blame] | 90 | @contextfactory |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 91 | def nested(*contexts): |
| 92 | """Support multiple context managers in a single with-statement. |
| 93 | |
| 94 | Code like this: |
| 95 | |
| 96 | with nested(A, B, C) as (X, Y, Z): |
| 97 | <body> |
| 98 | |
| 99 | is equivalent to this: |
| 100 | |
| 101 | with A as X: |
| 102 | with B as Y: |
| 103 | with C as Z: |
| 104 | <body> |
| 105 | |
| 106 | """ |
| 107 | exits = [] |
| 108 | vars = [] |
Guido van Rossum | f669436 | 2006-03-10 02:28:35 +0000 | [diff] [blame] | 109 | exc = (None, None, None) |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 110 | try: |
| 111 | try: |
| 112 | for context in contexts: |
| 113 | mgr = context.__context__() |
| 114 | exit = mgr.__exit__ |
| 115 | enter = mgr.__enter__ |
| 116 | vars.append(enter()) |
| 117 | exits.append(exit) |
| 118 | yield vars |
| 119 | except: |
| 120 | exc = sys.exc_info() |
| 121 | finally: |
| 122 | while exits: |
| 123 | exit = exits.pop() |
| 124 | try: |
Guido van Rossum | f669436 | 2006-03-10 02:28:35 +0000 | [diff] [blame] | 125 | if exit(*exc): |
| 126 | exc = (None, None, None) |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 127 | except: |
| 128 | exc = sys.exc_info() |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 129 | if exc != (None, None, None): |
Nick Coghlan | da2268f | 2006-04-24 04:37:15 +0000 | [diff] [blame] | 130 | # Don't rely on sys.exc_info() still containing |
| 131 | # the right information. Another exception may |
| 132 | # have been raised and caught by an exit method |
| 133 | raise exc[0], exc[1], exc[2] |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 134 | |
| 135 | |
Nick Coghlan | a7e820a | 2006-04-25 10:56:51 +0000 | [diff] [blame] | 136 | class closing(object): |
| 137 | """Context to automatically close something at the end of a block. |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 138 | |
| 139 | Code like this: |
| 140 | |
| 141 | with closing(<module>.open(<arguments>)) as f: |
| 142 | <block> |
| 143 | |
| 144 | is equivalent to this: |
| 145 | |
| 146 | f = <module>.open(<arguments>) |
| 147 | try: |
| 148 | <block> |
| 149 | finally: |
| 150 | f.close() |
| 151 | |
| 152 | """ |
Nick Coghlan | a7e820a | 2006-04-25 10:56:51 +0000 | [diff] [blame] | 153 | def __init__(self, thing): |
| 154 | self.thing = thing |
| 155 | def __context__(self): |
| 156 | return self |
| 157 | def __enter__(self): |
| 158 | return self.thing |
| 159 | def __exit__(self, *exc_info): |
| 160 | self.thing.close() |