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 | |
Michael Foord | b3a8984 | 2010-06-30 12:17:50 +0000 | [diff] [blame] | 7 | __all__ = ["contextmanager", "closing", "ContextDecorator"] |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 8 | |
Michael Foord | b3a8984 | 2010-06-30 12:17:50 +0000 | [diff] [blame] | 9 | |
| 10 | class ContextDecorator(object): |
| 11 | "A base class or mixin that enables context managers to work as decorators." |
| 12 | def __call__(self, func): |
| 13 | @wraps(func) |
| 14 | def inner(*args, **kwds): |
| 15 | with self: |
| 16 | return func(*args, **kwds) |
| 17 | return inner |
| 18 | |
| 19 | |
Antoine Pitrou | 67b212e | 2011-01-08 09:55:31 +0000 | [diff] [blame] | 20 | class _GeneratorContextManager(ContextDecorator): |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 21 | """Helper for @contextmanager decorator.""" |
| 22 | |
| 23 | def __init__(self, gen): |
| 24 | self.gen = gen |
| 25 | |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 26 | def __enter__(self): |
| 27 | try: |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 28 | return next(self.gen) |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 29 | except StopIteration: |
| 30 | raise RuntimeError("generator didn't yield") |
| 31 | |
| 32 | def __exit__(self, type, value, traceback): |
| 33 | if type is None: |
| 34 | try: |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 35 | next(self.gen) |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 36 | except StopIteration: |
| 37 | return |
| 38 | else: |
| 39 | raise RuntimeError("generator didn't stop") |
| 40 | else: |
Guido van Rossum | 2cc30da | 2007-11-02 23:46:40 +0000 | [diff] [blame] | 41 | if value is None: |
| 42 | # Need to force instantiation so we can reliably |
| 43 | # tell if we get the same exception back |
| 44 | value = type() |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 45 | try: |
| 46 | self.gen.throw(type, value, traceback) |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 47 | raise RuntimeError("generator didn't stop after throw()") |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 48 | except StopIteration as exc: |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 49 | # Suppress the exception *unless* it's the same exception that |
| 50 | # was passed to throw(). This prevents a StopIteration |
| 51 | # raised inside the "with" statement from being suppressed |
| 52 | return exc is not value |
| 53 | except: |
| 54 | # only re-raise if it's *not* the exception that was |
| 55 | # passed to throw(), because __exit__() must not raise |
| 56 | # an exception unless __exit__() itself failed. But throw() |
| 57 | # has to raise the exception to signal propagation, so this |
| 58 | # fixes the impedance mismatch between the throw() protocol |
| 59 | # and the __exit__() protocol. |
| 60 | # |
| 61 | if sys.exc_info()[1] is not value: |
| 62 | raise |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 63 | |
| 64 | |
| 65 | def contextmanager(func): |
| 66 | """@contextmanager decorator. |
| 67 | |
| 68 | Typical usage: |
| 69 | |
| 70 | @contextmanager |
| 71 | def some_generator(<arguments>): |
| 72 | <setup> |
| 73 | try: |
| 74 | yield <value> |
| 75 | finally: |
| 76 | <cleanup> |
| 77 | |
| 78 | This makes this: |
| 79 | |
| 80 | with some_generator(<arguments>) as <variable>: |
| 81 | <body> |
| 82 | |
| 83 | equivalent to this: |
| 84 | |
| 85 | <setup> |
| 86 | try: |
| 87 | <variable> = <value> |
| 88 | <body> |
| 89 | finally: |
| 90 | <cleanup> |
| 91 | |
| 92 | """ |
Christian Heimes | 81ee3ef | 2008-05-04 22:42:01 +0000 | [diff] [blame] | 93 | @wraps(func) |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 94 | def helper(*args, **kwds): |
Antoine Pitrou | 67b212e | 2011-01-08 09:55:31 +0000 | [diff] [blame] | 95 | return _GeneratorContextManager(func(*args, **kwds)) |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 96 | return helper |
| 97 | |
| 98 | |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 99 | class closing(object): |
| 100 | """Context to automatically close something at the end of a block. |
Guido van Rossum | 1a5e21e | 2006-02-28 21:57:43 +0000 | [diff] [blame] | 101 | |
| 102 | Code like this: |
| 103 | |
| 104 | with closing(<module>.open(<arguments>)) as f: |
| 105 | <block> |
| 106 | |
| 107 | is equivalent to this: |
| 108 | |
| 109 | f = <module>.open(<arguments>) |
| 110 | try: |
| 111 | <block> |
| 112 | finally: |
| 113 | f.close() |
| 114 | |
| 115 | """ |
Thomas Wouters | 477c8d5 | 2006-05-27 19:21:47 +0000 | [diff] [blame] | 116 | def __init__(self, thing): |
| 117 | self.thing = thing |
| 118 | def __enter__(self): |
| 119 | return self.thing |
| 120 | def __exit__(self, *exc_info): |
| 121 | self.thing.close() |