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

Aaron Brady castironpi at gmail.com
Tue Nov 18 20:19:42 EST 2008


On Nov 18, 3:59 pm, Daniel <inva... at invalid.invalid> wrote:
> 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

There isn't a solution in the general case, because strings can be
executed.  However, 'inspect.currentframe()' and
'inspect.getsourcelines(object)' can handle some cases, and your idea
is (I believe) how getsourcelines works itself.  You can probably do
it without a context manager, e.g. 'print_next_lines( 5 )' or
'print_prior_lines( 2 )', dedenting as needed.



More information about the Python-list mailing list