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

Jerry Hill malaclypse2 at gmail.com
Tue Feb 1 13:15:46 EST 2011


On Tue, Feb 1, 2011 at 11:34 AM, Gerald Britton <gerald.britton at gmail.com>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:
    do_something()

-- 
Jerry
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20110201/ee9ccd42/attachment-0001.html>


More information about the Python-list mailing list