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

Wolfgang Rohdewald wolfgang at rohdewald.de
Tue Feb 1 11:04:44 EST 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

-- 
Wolfgang
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20110201/98fd1a13/attachment-0001.html>


More information about the Python-list mailing list