I mean to define a function print_echo
that replaces print
, such that in addition to printing the result of an expression it prints the expression itself.
If I simply pass the expression as a string and use eval
inside print_echo
, it will not know any variable local to the caller function.
My current code is
def print_echo( expr ) :
result = eval( expr )
print( expr + ' => ' + str( result ) + ' ' + str( type( result ) ) )
return
But when using
def my_func( params ) :
a = 2
print_echo( "a" )
I get (no surprise)
NameError: name 'a' is not defined
I mean to get
a => 2 <type 'int'>
I conceived two ways of working around this.
Use a Python like alternative for C preprocessor macros. Something like C Preprocessor Macro equivalent for Python
Pass all local variables to print_echo. Something like Passing all arguments of a function to another function
Since I find inconvenient aspects for each of the two, Is there any alternative to these?
Note that expr is a generic expression, not necessarily the name of a variable.