Introduce a context manager that temporarily overrides a UILayout's operator context. Instead of writing this: ```py default_op_context = layout.context layout.context = 'OTHER_VALUE' layout.do_stuff() layout.context = default_op_context ``` you can now write this: ```py from bl_ui_utils.layout import operator_context with operator_context(layout, 'OTHER_VALUE'): layout.do_stuff() ``` This is also exception-safe; it will always ensure the layout's operator context is restored when the `with` body is exited, regardless of whether that's done with an exception or regularly. Idea in-the-hallway approved by @Sergey.
20 lines
500 B
Python
20 lines
500 B
Python
# SPDX-License-Identifier: GPL-2.0-or-later
|
|
|
|
import contextlib
|
|
|
|
|
|
@contextlib.contextmanager
|
|
def operator_context(layout, op_context):
|
|
"""Context manager that temporarily overrides the operator context.
|
|
|
|
>>> with operator_context(layout, 'INVOKE_REGION_CHANNELS'):
|
|
... layout.operator("anim.channels_delete")
|
|
"""
|
|
|
|
orig_context = layout.operator_context
|
|
layout.operator_context = op_context
|
|
try:
|
|
yield
|
|
finally:
|
|
layout.operator_context = orig_context
|