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

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

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

  2. Gerald Britton

    alex23 Guest

    On Feb 2, 1:28 am, 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.


    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.
    alex23, Feb 3, 2011
    #2
    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:
    349
    Victor Bazarov
    Mar 14, 2007
  2. padma
    Replies:
    0
    Views:
    328
    padma
    Oct 3, 2007
  3. Daniel
    Replies:
    4
    Views:
    278
    Daniel
    Nov 20, 2008
  4. Metalone
    Replies:
    0
    Views:
    329
    Metalone
    Jan 6, 2010
  5. Gerald Britton
    Replies:
    0
    Views:
    213
    Gerald Britton
    Feb 1, 2011
Loading...

Share This Page