|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +from contextlib import contextmanager |
| 4 | +import sys |
| 5 | + |
| 6 | + |
| 7 | +class ContextTest: |
| 8 | + |
| 9 | + _context_nr: int |
| 10 | + |
| 11 | + @property |
| 12 | + def context_nr(self): |
| 13 | + return self._context_nr |
| 14 | + |
| 15 | + @context_nr.setter |
| 16 | + def context_nr(self, value): |
| 17 | + self._context_nr = value |
| 18 | + |
| 19 | + def __init__(self, context_nr): |
| 20 | + self._context_nr = context_nr |
| 21 | + print(f'created with {self._context_nr}') |
| 22 | + |
| 23 | + def __enter__(self): |
| 24 | + print(f'entering {self._context_nr}') |
| 25 | + return self |
| 26 | + |
| 27 | + def __exit__(self, exception_type, exception_value, backtrace): |
| 28 | + print(f'exiting {self._context_nr}') |
| 29 | + if exception_type: |
| 30 | + print(f'exception in context {self._context_nr}:') |
| 31 | + print('\t', exception_type, exception_value, backtrace) |
| 32 | + return |
| 33 | + print(f'no exception in context {self._context_nr}') |
| 34 | + |
| 35 | + |
| 36 | +@contextmanager |
| 37 | +def label(name): |
| 38 | + print(f'entering label({name})') |
| 39 | + yield name |
| 40 | + print(f'exiting label({name})') |
| 41 | + |
| 42 | + |
| 43 | +def main(): |
| 44 | + with ContextTest(1) as context_1, ContextTest(2) as context_2: |
| 45 | + print(f'in context {context_1.context_nr}') |
| 46 | + print(f'in context {context_2.context_nr}') |
| 47 | + with label('foo') as foo_label, label('bar') as bar_label: |
| 48 | + print(foo_label, bar_label) |
| 49 | + with ContextTest(1) as context_1, ContextTest(2) as context_2: |
| 50 | + print(f'in context {context_1.context_nr}') |
| 51 | + raise Exception() |
| 52 | + # print(f'in context {context_2.context_nr}') |
| 53 | + return 0 |
| 54 | + |
| 55 | + |
| 56 | +if __name__ == '__main__': |
| 57 | + STATUS = main() |
| 58 | + sys.exit(STATUS) |
0 commit comments