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

G

Gerald Britton

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:
 
A

alex23

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

Actually, it occurs to me the simplest way is to use the context
manager itself to keep track:

class F(object):
def __init__(self):
self.in_context = False

def __enter__(self):
self.in_context = True
return self

def __exit__(self, exc_type, exc_val, exc_tb):
self.in_context = False
.... print f.in_context
....
TrueFalse

Hope this helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top