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

Discussion in 'Python' started by Gerald Britton, Feb 1, 2011.

  1. 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
    Gerald Britton, Feb 1, 2011
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. yogesh
    Replies:
    1
    Views:
    354
    Victor Bazarov
    Mar 14, 2007
  2. padma
    Replies:
    0
    Views:
    334
    padma
    Oct 3, 2007
  3. Daniel
    Replies:
    4
    Views:
    282
    Daniel
    Nov 20, 2008
  4. Metalone
    Replies:
    0
    Views:
    332
    Metalone
    Jan 6, 2010
  5. Gerald Britton
    Replies:
    1
    Views:
    261
    alex23
    Feb 3, 2011
Loading...

Share This Page