Context manager that copies the passed or current context object and sets it as the current context variable. If no context is found, a new ``ClientContext`` object is created. It mainly ensures the context variable is reset to the previous value once the executed code returns.
(ctx=None)
| 69 | |
| 70 | @contextmanager |
| 71 | def start_as_current_context(ctx=None): |
| 72 | """ |
| 73 | Context manager that copies the passed or current context object and sets |
| 74 | it as the current context variable. If no context is found, a new |
| 75 | ``ClientContext`` object is created. It mainly ensures the context variable |
| 76 | is reset to the previous value once the executed code returns. |
| 77 | |
| 78 | Example usage: |
| 79 | |
| 80 | def my_feature(): |
| 81 | with start_as_current_context(): |
| 82 | register_feature_id('MY_FEATURE') |
| 83 | pass |
| 84 | |
| 85 | :type ctx: ClientContext |
| 86 | :param ctx: The client context object to set as the new context variable. |
| 87 | If not provided, the current or a new context variable is used. |
| 88 | """ |
| 89 | current = ctx or get_context() |
| 90 | if current is None: |
| 91 | new = ClientContext() |
| 92 | else: |
| 93 | new = deepcopy(current) |
| 94 | token = set_context(new) |
| 95 | try: |
| 96 | yield |
| 97 | finally: |
| 98 | reset_context(token) |
| 99 | |
| 100 | |
| 101 | def with_current_context(hook=None): |