Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > How can I tell if I am inside a context manager?

Reply
Thread Tools

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

 
 
Gerald Britton
Guest
Posts: n/a
 
      02-01-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
 
Reply With Quote
 
 
 
 
alex23
Guest
Posts: n/a
 
      02-03-2011
On Feb 2, 1:28*am, Gerald Britton <(E-Mail Removed)> wrote:
> 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

>>> f = F()
>>> f.in_context

False

>>> with F() as f:

.... print f.in_context
....
True
>>> print f.in_context

False

Hope this helps.

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Re: How include a large array? Edward A. Falk C Programming 1 04-04-2013 08:07 PM
How can I tell if I am inside a context manager? Gerald Britton Python 0 02-01-2011 04:34 PM
CAN any one tell it whats the code tell it yogesh C++ 1 03-14-2007 01:12 PM
Strange Context Error: Context 0x197ee0 is disconnected in VS 2005 =?Utf-8?B?U3VuU21pbGU=?= ASP .Net 0 01-10-2006 03:59 PM
Context.Items vs Context.Handler (passing values between pages) VS_NET_DEV ASP .Net 2 05-25-2004 01:16 PM



Advertisments