How can I tell if I am inside a context manager?

alex23 wuwei23 at
Wed Feb 2 23:45:46 EST 2011

On Feb 2, 1:28 am, Gerald Britton <gerald.brit... at> wrote:
> I'd like to know how (perhaps with the inspect module) I can tell if I
> am running in a context manager.

Actually, it occurs to me the simplest way is to use the context
manager itself to keep track:

class F(object):
    def __init__(self):
        self.in_context = False

    def __enter__(self):
        self.in_context = True
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.in_context = False

>>> f = F()
>>> f.in_context

>>> with F() as f:
...   print f.in_context
>>> print f.in_context

Hope this helps.

More information about the Python-list mailing list