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

alex23 wuwei23 at gmail.com
Wed Feb 2 23:38:36 EST 2011


Gerald Britton <gerald.brit... at 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.



More information about the Python-list mailing list