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 | |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 13 | def __enter__(self): |
| 14 | try: |
| 15 | return self.gen.next() |
| 16 | except StopIteration: |
| 17 | raise RuntimeError("generator didn't yield") |
| 18 | |
| 19 | def __exit__(self, type, value, traceback): |
| 20 | if type is None: |
| 21 | try: |
| 22 | self.gen.next() |
| 23 | except StopIteration: |
| 24 | return |
| 25 | else: |
| 26 | raise RuntimeError("generator didn't stop") |
| 27 | else: |
| 28 | try: |
| 29 | self.gen.throw(type, value, traceback) |
Phillip J. Eby | 6edd258 | 2006-03-25 00:28:24 +0000 | [diff] [blame] | 30 | raise RuntimeError("generator didn't stop after throw()") |
Phillip J. Eby | 93149d9 | 2006-04-10 17:56:29 +0000 | [diff] [blame] | 31 | except StopIteration, exc: |
Phillip J. Eby | 9388020 | 2006-04-03 21:20:07 +0000 | [diff] [blame] | 32 | # Suppress the exception *unless* it's the same exception that |
| 33 | # was passed to throw(). This prevents a StopIteration |
| 34 | # raised inside the "with" statement from being suppressed |
Phillip J. Eby | 93149d9 | 2006-04-10 17:56:29 +0000 | [diff] [blame] | 35 | return exc is not value |
Phillip J. Eby | 6edd258 | 2006-03-25 00:28:24 +0000 | [diff] [blame] | 36 | except: |
Phillip J. Eby | ccc7bb4 | 2006-03-25 04:32:12 +0000 | [diff] [blame] | 37 | # only re-raise if it's *not* the exception that was |
| 38 | # passed to throw(), because __exit__() must not raise |
| 39 | # an exception unless __exit__() itself failed. But throw() |
| 40 | # has to raise the exception to signal propagation, so this |
| 41 | # fixes the impedance mismatch between the throw() protocol |
| 42 | # and the __exit__() protocol. |
| 43 | # |
Phillip J. Eby | 6edd258 | 2006-03-25 00:28:24 +0000 | [diff] [blame] | 44 | if sys.exc_info()[1] is not value: |
| 45 | raise |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 46 | |
| 47 | |
Nick Coghlan | a7e820a | 2006-04-25 10:56:51 +0000 | [diff] [blame] | 48 | def contextfactory(func): |
| 49 | """@contextfactory decorator. |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 50 | |
| 51 | Typical usage: |
| 52 | |
Brett Cannon | 1e01397 | 2006-04-29 21:29:50 +0000 | [diff] [blame] | 53 | @contextfactory |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 54 | def some_generator(<arguments>): |
| 55 | <setup> |
| 56 | try: |
| 57 | yield <value> |
| 58 | finally: |
| 59 | <cleanup> |
| 60 | |
| 61 | This makes this: |
| 62 | |
| 63 | with some_generator(<arguments>) as <variable>: |
| 64 | <body> |
| 65 | |
| 66 | equivalent to this: |
| 67 | |
| 68 | <setup> |
| 69 | try: |
| 70 | <variable> = <value> |
| 71 | <body> |
| 72 | finally: |
| 73 | <cleanup> |
| 74 | |
| 75 | """ |
| 76 | def helper(*args, **kwds): |
Nick Coghlan | a7e820a | 2006-04-25 10:56:51 +0000 | [diff] [blame] | 77 | return GeneratorContext(func(*args, **kwds)) |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 78 | try: |
| 79 | helper.__name__ = func.__name__ |
| 80 | helper.__doc__ = func.__doc__ |
Phillip J. Eby | 35fd142 | 2006-03-28 00:07:24 +0000 | [diff] [blame] | 81 | helper.__dict__ = func.__dict__ |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 82 | except: |
| 83 | pass |
| 84 | return helper |
| 85 | |
| 86 | |
Nick Coghlan | a7e820a | 2006-04-25 10:56:51 +0000 | [diff] [blame] | 87 | @contextfactory |
Guido van Rossum | da5b701 | 2006-05-02 19:47:52 +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: |
| 108 | try: |
Guido van Rossum | da5b701 | 2006-05-02 19:47:52 +0000 | [diff] [blame^] | 109 | for mgr in managers: |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 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() |
| 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() |