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

Gerald Britton gerald.britton at
Tue Feb 1 13:38:34 EST 2011

"Perhaps something like this:"

>>x = open('somefile')
>>if hasattr(x, '__enter__'):
>>    return false
>>with open('somefile') as x:
>>    do_something()

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

>>> x = f()
>>> hasattr(x, '__enter__')
>>> with f() as x:


As you can see, the object has a '__enter__' method regardless of how
it was created.  Whatever the test, it needs to return False in the
first case and True in the second case, without modifying the class

Gerald Britton

More information about the Python-list mailing list