Context workaround. The built-in ``@contextmanager`` utility does not work well when wrapping other contexts, as the traceback is wrong when the wrapped context raises. This solves this problem and can be used instead of ``@contextmanager`` in this example:: @contextma
| 45 | |
| 46 | |
| 47 | class FallbackContext: |
| 48 | """Context workaround. |
| 49 | |
| 50 | The built-in ``@contextmanager`` utility does not work well |
| 51 | when wrapping other contexts, as the traceback is wrong when |
| 52 | the wrapped context raises. |
| 53 | |
| 54 | This solves this problem and can be used instead of ``@contextmanager`` |
| 55 | in this example:: |
| 56 | |
| 57 | @contextmanager |
| 58 | def connection_or_default_connection(connection=None): |
| 59 | if connection: |
| 60 | # user already has a connection, shouldn't close |
| 61 | # after use |
| 62 | yield connection |
| 63 | else: |
| 64 | # must've new connection, and also close the connection |
| 65 | # after the block returns |
| 66 | with create_new_connection() as connection: |
| 67 | yield connection |
| 68 | |
| 69 | This wrapper can be used instead for the above like this:: |
| 70 | |
| 71 | def connection_or_default_connection(connection=None): |
| 72 | return FallbackContext(connection, create_new_connection) |
| 73 | """ |
| 74 | |
| 75 | def __init__(self, provided, fallback, *fb_args, **fb_kwargs): |
| 76 | self.provided = provided |
| 77 | self.fallback = fallback |
| 78 | self.fb_args = fb_args |
| 79 | self.fb_kwargs = fb_kwargs |
| 80 | self._context = None |
| 81 | |
| 82 | def __enter__(self): |
| 83 | if self.provided is not None: |
| 84 | return self.provided |
| 85 | context = self.fallback( |
| 86 | *self.fb_args, **self.fb_kwargs |
| 87 | ) |
| 88 | value = context.__enter__() |
| 89 | self._context = context |
| 90 | return value |
| 91 | |
| 92 | def __exit__(self, *exc_info): |
| 93 | if self._context is not None: |
| 94 | return self._context.__exit__(*exc_info) |
| 95 | |
| 96 | __class_getitem__ = classmethod(types.GenericAlias) |
| 97 | |
| 98 | |
| 99 | class getitem_property: |
no outgoing calls