How can I conveniently print an expression?

Jan Dries jdries at mail.com
Sun Dec 31 19:02:20 CET 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
> 
> 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