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

Gerald Britton gerald.britton at gmail.com
Tue Feb 1 16:28:02 CET 2011


I'd like to know how (perhaps with the inspect module) I can tell if I
am running in a context manager.

e.g.

class f():
    def __init__(s): pass
    def __enter__(s): return s
    def __exit__(s,a,b,c): return None

def g():
    x = f()
    # insert code here to return False, since I am not in a context
manager on f:
    with h as f():
        # insert code here to return True, since I am in a context manager on f:

-- 
Gerald Britton



More information about the Python-list mailing list