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

Wolfgang Rohdewald wolfgang at
Tue Feb 1 17:04:44 CET 2011

On Dienstag 01 Februar 2011, Gerald Britton wrote:
> I'd like to know how (perhaps with the inspect module) I can
> tell if I am running in a context manager.

class f(object):
    def __init__(self): 
        self.inContext = False
    def __enter__(self): 
        self.inContext = True
        return self
    def __exit__(self,a,b,c):
        self.inContext = False
        return None

x = f()
print 'not within:', x.inContext
with f() as h:
    print 'within:', h.inContext

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the Python-list mailing list