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
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
 
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 1 02-03-2011 04:45 AM
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