how to acces the block inside of a context manager as sourcecode

Daniel invalid at invalid.invalid
Tue Nov 18 16:59:43 EST 2008


Hello,

I need to access the code inside of a context manager, i.e. the call to

with myManager(v=5) as x:
	a=b
	c=sin(x)


should cause the following output (minus the first line, if that's easier):


with myManager(v=5) as x: # I could live without this line
	a=b
	c=sin(x)


I can get the line number from the traceback (see below), and try to
find the block in the source, but that seems ugly to me.



class MyManager(object):
    def __init__(self,name='name'):
	# how to access the source code inside of the with block ?
        f = traceback.extract_stack()
        print f[0]

    def __enter__(self):
        pass

    def __exit__(self,type,value,traceback):
        if type is not None:
            print 'exception'
        pass



Any ideas?

Daniel



More information about the Python-list mailing list