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

alex23 wuwei23 at gmail.com
Thu Feb 3 05:45:46 CET 2011


On Feb 2, 1:28 am, Gerald Britton <gerald.brit... at gmail.com> 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
False

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

Hope this helps.




More information about the Python-list mailing list