在Python 2.7中,我曾经能够使用以下代码(我正在使用emcee包:]
from emcee import moves
emcee_moves = ['KDEMove(),0.5', 'DEMove(),0.5']
mv = [(eval("moves." + _)) for _ in emcee_moves]
之所以使用它,是因为我通过输入参数文件(这是一个更大的代码的一小部分)提供“动作”,这意味着它们被当作字符串读取。现在在Python 3.x中抛出:
*** NameError: name 'moves' is not defined
这显然与this wont fix bug有关,在这个旧问题中提到:Eval scope in Python 2 vs. 3。
我也读过,一般不建议使用eval()
。我的问题是:如何复制上面在Python 2.7中可用的代码?
正如Pete所说,您的示例适用于python 3.6.8。但是,做您想要的另一种方法是:
from emcee import moves
emcee_moves = [('KDEMove', 0.5), ('DEMove', 0.5)]
mv = [(getattr(moves, method)(), val) for method, val in emcee_moves]
您总是可以用常规循环替换列表推导。花哨的少,但具有相同的功能。
尽管I have Python 3.8.0 and the code works as expected - without any errors.
,正如我的评论所说,仍然可以在没有任何eval()
的情况下进行这些操作。
[我正在将Jupyter笔记本与Python 3配合使用,并且对我有效,没有任何错误