How can I conveniently print an expression?

Issac Trotts trotts at llnl.gov
Sun Dec 31 22:41:21 CET 2000


Thanks for the clever trick.  It works!

Issac


On Sun, Dec 31, 2000 at 07:02:20PM +0100, Jan Dries wrote:
> 
> 
> Issac Trotts wrote:
> > 
> > In Python, one might naively try something like
> > 
> > def printexpr(expr_string):
> >   expr = eval(expr_string)
> >   print expr_string+' = '+`expr`
> > 
> > which would be used to say things like
> > 
> > printexpr('len(sys.argv)')
> > 
> > but of course this does not always work because when Python executes
> > eval(expr_string), it assumes that the elements of the expression
> > specified by expr_string are to be found in the global scope. 
> >
> > If there were some mechanism that allowed us to access the variables
> > of a calling function from within a called function, then the problem
> > would be solved.  Does anyone know of such a mechanism?
> 
> I once came up with a solution for this. The following should do the
> trick for you:
> 
> from sys import exc_info
> 
> def caller_symbols():
>     try:
>         raise StandardError
>     except StandardError:
>         t = exc_info()[2].tb_frame
>         return (t.f_back.f_back.f_globals,t.f_back.f_back.f_locals)
> 
> def printexpr(expr_string):
>     caller_globals,caller_locals = caller_symbols()
>     expr = eval(expr_string,caller_globals,caller_locals)
>     print expr_string+' = '+`expr`
> 
> 
> Regards,
> Jan




More information about the Python-list mailing list