How can I conveniently print an expression?
jdries at mail.com
Sun Dec 31 13:02:20 EST 2000
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
> 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
t = exc_info().tb_frame
caller_globals,caller_locals = caller_symbols()
expr = eval(expr_string,caller_globals,caller_locals)
print expr_string+' = '+`expr`
More information about the Python-list