打印表达式并回显它 [英] Print expression and also echo it
问题描述
我的意思是定义一个替换print
的函数print_echo
,这样,除了打印表达式的结果外,它还会打印表达式本身.
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.
如果我只是将表达式作为字符串传递并在print_echo
中使用eval
,它将不会知道调用方函数本地的任何变量.
我当前的代码是
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
但是使用时
def my_func( params ) :
a = 2
print_echo( "a" )
我得到了(不足为奇)
NameError: name 'a' is not defined
我的意思是
a => 2 <type 'int'>
我设想了两种解决方法.
I conceived two ways of working around this.
-
对C预处理器宏使用类似Python的替代方法. 类似于与Python等效的C预处理器宏
Use a Python like alternative for C preprocessor macros. Something like C Preprocessor Macro equivalent for Python
将所有局部变量传递给print_echo. 类似于将一个函数的所有参数传递给另一个函数
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?
请注意,expr是通用表达式,不一定是变量的名称.
Note that expr is a generic expression, not necessarily the name of a variable.
推荐答案
eval()
仅考虑全局名称空间以及调用它的本地名称空间.
eval()
only takes the global namespace, and the namespace local to where it is called, into account.
在您的情况下,您需要将调用print_echo
的名称空间(即,调用eval
的父"名称空间)作为本地名称空间,可以使用 inspect
模块并传递给eval
作为参数.
In your case, you need the namespace of where print_echo
is called (i.e., the "parent" namespace of where eval
is called) as the local namespace, which you can get by using the inspect
module and pass to eval
as an argument.
import inspect
def print_echo(expr):
outer_locals = inspect.currentframe().f_back.f_locals
result = eval(expr, globals(), outer_locals)
print(expr, '=>', result, type(result))
a = 2
print_echo('a')
def f():
b = 3
print_echo('b')
f()
Python 3输出:
Python 3 output:
a => 2 <class 'int'>
b => 3 <class 'int'>
这篇关于打印表达式并回显它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!