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

Gerald Britton gerald.britton at gmail.com
Tue Feb 1 11:34:11 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

yes, of course, but in this case I may not modify the class.  try it with open:

x = open('somefile')
# return false since not in a context
with open('somefile') as x
# return true since in a context.


-- 
Wolfgang

-- 
Gerald Britton



More information about the Python-list mailing list