I am trying to refactor the following:
with MyContext() as ctx:
ctx.some_function()
...into something more like this:
with MyContext():
some_function()
How can I detect in the body of some_function that I have called it within the context of MyContext()? I would prefer that this is done in a thread-safe way.
This appears to be possible because it is done in the builtin decimal module:
from decimal import localcontext
with localcontext() as ctx:
ctx.prec = 42 # Perform a high precision calculation
s = calculate_something()
It sounds like you want to crawl up the call stack, looking for evidence of a context manager.
output: