python中eval函数的作用域 [英] scope of eval function in python

查看:147
本文介绍了python中eval函数的作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下示例:

i=7
j=8
k=10
def test():
    i=1
    j=2
    k=3
    return dict((name,eval(name)) for name in ['i','j','k'])

它返回:

>>> test()
{'i': 7, 'k': 10, 'j': 8}

为什么eval不考虑函数内部定义的变量?从文档中,您可以选择传递globals和locals字典.到底是什么意思?最后,如何修改此小写字母以使其正常工作?

Why eval does not take into consideration the variables defined inside the function? From the documentation, optionally you can pass a globals and a locals dictionary. What does it means?Finally, how can I modify this small case to make it work?

推荐答案

生成器被实现为函数作用域:

在类块中定义的名称范围仅限于该类 堵塞;它没有扩展到方法的代码块–这 包括生成器表达式,因为它们是使用 功能范围.

The scope of names defined in a class block is limited to the class block; it does not extend to the code blocks of methods – this includes generator expressions since they are implemented using a function scope.

因此,dict()构造函数内部的生成器具有自己的locals()字典.现在,让我们看一下 Py_eval的源代码,特别是在globals()locals()均为无:

So, the generator inside the dict() constructor has its own locals() dictionary. Now let's take a look at Py_eval's source code, specially when both globals() and locals() are None:

if (globals == Py_None) {
        globals = PyEval_GetGlobals();
        if (locals == Py_None)
            locals = PyEval_GetLocals();
    }

因此,对于您的示例, PyEval_GetLocals() 在循环执行的瞬间,globals()将成为全局字典.请注意,在函数内部定义的ijk不在生成器的本地范围内,而是在其封闭范围内:

So, for your example PyEval_GetLocals() will be empty at the moment the loop is executing and globals() will be the global dictionary. Note that i, j and k defined inside the function are not in local scope of generator, rather they are in its enclosing scope:

>>> dict((name,eval(name, globals(), {})) for name in ['i', 'j', 'k'])
{'i': 7, 'k': 10, 'j': 8}

这篇关于python中eval函数的作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆