Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #55719 > unrolled thread
| Started by | Gerald Britton <gerald.britton@gmail.com> |
|---|---|
| First post | 2011-02-01 13:38 -0500 |
| Last post | 2011-02-02 20:38 -0800 |
| Articles | 2 — 2 participants |
Back to article view | Back to comp.lang.python
This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by
below is the oldest one visible, not the original post.
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
| From | Gerald Britton <gerald.britton@gmail.com> |
|---|---|
| Date | 2011-02-01 13:38 -0500 |
| Subject | Re: How can I tell if I am inside a context manager? |
| Message-ID | <mailman.1549.1296585517.6505.python-list@python.org> |
"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
[toc] | [next] | [standalone]
| From | alex23 <wuwei23@gmail.com> |
|---|---|
| Date | 2011-02-02 20:38 -0800 |
| Message-ID | <dc9f3196-91c3-46b0-941f-5788e43ed27c@f21g2000vbg.googlegroups.com> |
| In reply to | #55719 |
Gerald Britton <gerald.brit...@gmail.com> wrote: > >>> 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. If you control all instantiation and this is to simplify code further on, could you have a ContextF that's a child of F? The only difference would then be the protocol methods. A use case could also help here.
[toc] | [prev] | [standalone]
Back to top | Article view | comp.lang.python
csiph-web