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

Gerald Britton gerald.britton at gmail.com
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__')
True
>>> with f() as x:
	hasattr(x,'__enter__')

	
True
>>>

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
definition.


Gerald Britton



More information about the Python-list mailing list