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

Jerry Hill malaclypse2 at
Tue Feb 1 19:15:46 CET 2011

On Tue, Feb 1, 2011 at 11:34 AM, Gerald Britton <gerald.britton at>wrote:

> x = open('somefile')
> # return false since not in a context
> with open('somefile') as x
> # return true since in a context.

Perhaps something like this:

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

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the Python-list mailing list