Here is an example of using global for this task - in what I consider relatively safe:
from contextlib import contextmanager from functools import wraps _within_special_context = False @contextmanager def flag(): global _within_special_context _within_special_context = True try: yield finally: _within_special_context = False
Result:
True Traceback (most recent call last): File "/Users/gareth/Development/so/test.py", line 39, in <module> foo() File "/Users/gareth/Development/so/test.py", line 24, in internal f(*args, **kwargs) File "/Users/gareth/Development/so/test.py", line 32, in foo bar() File "/Users/gareth/Development/so/test.py", line 26, in internal raise Exception("No nested calls!") Exception: No nested calls!
Using the context manager ensures that the variable is not set. You can simply use try/finally , but if you want to change the behavior for different situations, the context manager can be made flexible and reusable.
source share