Is there a way to detect if running code is being executed inside a context manager?

2024/5/20 18:06:46

As the title states, is there a way to do something like this:

def call_back():if called inside context:print("running in context")else:print("called outside context")

And this would result in:

with CTM() as context:call_back()
call_back()>>> "running in context"
>>> "called outside context"
Answer

As @chepner wrote in the comments of the question

Not [possible] without using the inspect module, I'd think. There's nothing really special about the block of code in a with statement, aside from the guarantee that context.__enter__ will be called prior to executing it and context.__exit__ will be called after.

Then @larsks suggested that if you have control over the context manager...

... you could update some global or object-specific state to indicate whether you are inside the context manager or not.

This seems to be the solution finally adopted by @new-dev-123.

Here you have that solution:

class CTM:def __init__(self):self._is_in_context = False   def __enter__(self):self._is_in_context = Truereturn selfdef __exit__(self, *args, **kwargs):self._is_in_context = Falsedef call_back(self):if self._is_in_context:print("running in context")else:print("called outside context")
>>> with CTM() as context:
...     context.call_back()
running in context
>>> context.call_back()
called outside context

If you want the same behaviour for multiple methods, or to keep responsibilities separated, you can use a decorator.

def reveal_context(func):def inner(self, *args, **kwargs):if self._is_in_context:print("running in context")else:print("called outside context") return func(self, *args, **kwargs)return innerclass CTM:def __init__(self):self._is_in_context = Falsedef __enter__(self):self._is_in_context = Truereturn selfdef __exit__(self, *args, **kwargs):self._is_in_context = False@reveal_contextdef call_back(self):pass
https://en.xdnf.cn/q/73069.html

Related Q&A

Adding title to the column of subplot below suptitle

Is there a simple way to add in to my original code so that I can add another title to both column of my subplot? for example like somewhere in the pink region shown in the picture below.Someone refer…

Conditional Inheritance based on arguments in Python

Being new to OOP, I wanted to know if there is any way of inheriting one of multiple classes based on how the child class is called in Python. The reason I am trying to do this is because I have multip…

Slice endpoints invisibly truncated

>>> class Potato(object): ... def __getslice__(self, start, stop): ... print start, stop ... >>> sys.maxint 9223372036854775807 >>> x = sys.maxint + 69 >…

Selenium Webdriver with Java vs. Python

Im wondering what the pros and cons are of using Selenium Webdriver with the python bindings versus Java. So far, it seems like going the java route has much better documentation. Other than that, it s…

asyncio - how many coroutines?

I have been struggling for a few days now with a python application where I am expecting to look for a file or files in a folder and iterate through the each file and each record in it and create objec…

Calculating a 3D gradient with unevenly spaced points

I currently have a volume spanned by a few million every unevenly spaced particles and each particle has an attribute (potential, for those who are curious) that I want to calculate the local force (ac…

deleting every nth element from a list in python 2.7

I have been given a task to create a code for. The task is as follows:You are the captain of a sailing vessel and you and your crew havebeen captured by pirates. The pirate captain has all of you stand…

Bradley-Roth Adaptive Thresholding Algorithm - How do I get better performance?

I have the following code for image thresholding, using the Bradley-Roth image thresholding method. from PIL import Image import copy import time def bradley_threshold(image, threshold=75, windowsize=5…

How to display all images in a directory with flask [duplicate]

This question already has answers here:Reference template variable within Jinja expression(1 answer)Link to Flask static files with url_for(2 answers)Closed 6 years ago.I am trying to display all image…

Reindex sublevel of pandas dataframe multiindex

I have a time series dataframe and I would like to reindex it by Trials and Measurements.Simplified, I have this:value Trial 1 0 131 32 42 3 NaN4 123…