Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #55719

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

References <AANLkTim2zAf2_7MpHgDPfHB=4jq2=qm1N8pWXO-=16M-@mail.gmail.com>
Date 2011-02-01 13:38 -0500
Subject Re: How can I tell if I am inside a context manager?
From Gerald Britton <gerald.britton@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.1549.1296585517.6505.python-list@python.org> (permalink)

Show all headers | View raw


"Perhaps something like this:"

>>x = open('somefile')
>>if hasattr(x, '__enter__'):
>>    return false
>>with open('somefile') as x:
>>    do_something()

>>> class f():
    def __init__(s): pass
    def __enter__(s): return s
    def __exit__(s,a,b,c): return None

>>> x = f()
>>> hasattr(x, '__enter__')
True
>>> with f() as x:
	hasattr(x,'__enter__')

	
True
>>>

As you can see, the object has a '__enter__' method regardless of how
it was created.  Whatever the test, it needs to return False in the
first case and True in the second case, without modifying the class
definition.


Gerald Britton

Back to comp.lang.python | Previous | NextNext in thread | Find similar | Unroll thread


Thread

Re: How can I tell if I am inside a context manager? Gerald Britton <gerald.britton@gmail.com> - 2011-02-01 13:38 -0500
  Re: How can I tell if I am inside a context manager? alex23 <wuwei23@gmail.com> - 2011-02-02 20:38 -0800

csiph-web