英文文档:

eval(expressionglobals=Nonelocals=None)
The arguments are a string and optional globals and locals. If provided, globals must be a dictionary. If provided, locals can be any mapping object.
The expression argument is parsed and evaluated as a Python expression (technically speaking, a condition list) using the globals and localsdictionaries as global and local namespace. If the globals dictionary is present and lacks ‘__builtins__’, the current globals are copied into globals before expression is parsed. This means that expression normally has full access to the standard builtins module and restricted environments are propagated. If the locals dictionary is omitted it defaults to the globals dictionary. If both dictionaries are omitted, the expression is executed in the environment where eval() is called. The return value is the result of the evaluated expression. Syntax errors are reported as exceptions. Example:
>>> x = 1
>>> eval('x+1')
2

This function can also be used to execute arbitrary code objects (such as those created by compile()). In this case pass a code object instead of a string. If the code object has been compiled with 'exec' as the mode argument, eval()‘s return value will be None.

Hints: dynamic execution of statements is supported by the exec() function. The globals() and locals() functions returns the current global and local dictionary, respectively, which may be useful to pass around for use by eval() or exec().
See ast.literal_eval() for a function that can safely evaluate strings with expressions containing only literals.
说明:
执行动态语句,返回语句执行的值:
>>> eval('1+2+3+4')
10

 

第一个参数为语句字符串,globals参数和locals参数为可选参数,如果提供,globals参数必须是字典,locals参数是mapping对象

globals参数用来指定代码执行时可以使用的全局变量以及收集代码执行后的全局变量

>>> g = {'num':2}

>>> eval('num + 2') #num未定义
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
eval('num + 2')
File "<string>", line 1, in <module>
NameError: name 'num' is not defined >>> eval('num + 2',g) #g中有定义num,可执行
4

locals参数用来指定代码执行时可以使用的局部变量以及收集代码执行后的局部变量

>>> g = {'num1':2}
>>> l = {'num2':4}
>>> eval('num1+num2',g,l)
6

为了保证代码成功运行,globals参数字典不包含_builtins__这个key时,Python会自动添加一个key为__builtins__,value为builtins模块的引用,如果确实要限制代码不使用builtins模块,需要在global添加一个key为__builtins__,value为{}的项即可,

>>> g = {}
>>> eval('abs(-1)',g)
1 >>> g = {'__builtins__':{}}
>>> eval('abs(-1)',g) #不能使用内置函数了
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
eval('abs(-1)',g)
File "<string>", line 1, in <module>
NameError: name 'abs' is not defined

当globals参数不提供时,Python默认使用globals()函数返回的字典来调用,当locals参数不提供时,默认使用globals参数去调用

>>> num = 1
>>> eval('num+2')
3 >>> globals() #返回字典中含有num的key
{'__doc__': None, 'num': 1, '__package__': None, '__name__': '__main__', '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__builtins__': <module 'builtins' (built-in)>} >>> eval('num+2',{}) #locals参数未提供,locals参数=globals参数
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
eval('num+2',{})
File "<string>", line 1, in <module>
NameError: name 'num' is not defined >>> l = locals()
>>> eval('num+2',{},l) #locals参数含有num的key,能求值
3 >>> locals()
{'__doc__': None, 'l': {...}, 'num': 1, '__package__': None, '__name__': '__main__', '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__builtins__': <module 'builtins' (built-in)>}
>>>

  

 

转载

Python内置函数eval的更多相关文章

  1. python内置函数 eval()、exec()以及complie()函数

    1.eval函数 eval() 函数用来执行一个字符串表达式,并返回表达式的值. eval(expression[, globals[, locals]]) 参数 expression -- 表达式. ...

  2. python 内置函数eval()、exec()、compile()

    eval 函数的作用: 计算指定表达式的值.也就是说它要执行的python代码只能是单个表达式,而不是复杂的代码逻辑.    eval(source, globals=None, locals=Non ...

  3. python 内置函数input/eval(22)

    python的内置函数其实挺多的,其中input和eval算得上比较特殊,input属于交互式内置函数,eval函数能直接执行字符串表达式并返回表达式的值. 一.input函数 input是Pytho ...

  4. python内置函数

    python内置函数 官方文档:点击 在这里我只列举一些常见的内置函数用法 1.abs()[求数字的绝对值] >>> abs(-13) 13 2.all() 判断所有集合元素都为真的 ...

  5. python 内置函数和函数装饰器

    python内置函数 1.数学相关 abs(x) 取x绝对值 divmode(x,y) 取x除以y的商和余数,常用做分页,返回商和余数组成一个元组 pow(x,y[,z]) 取x的y次方 ,等同于x ...

  6. Python 内置函数笔记

    其中有几个方法没怎么用过, 所以没整理到 Python内置函数 abs(a) 返回a的绝对值.该参数可以是整数或浮点数.如果参数是一个复数,则返回其大小 all(a) 如果元组.列表里面的所有元素都非 ...

  7. 【转】python 内置函数总结(大部分)

    [转]python 内置函数总结(大部分) python 内置函数大讲堂 python全栈开发,内置函数 1. 内置函数 python的内置函数截止到python版本3.6.2,现在python一共为 ...

  8. python内置函数,匿名函数

    一.匿名函数 匿名函数:为了解决那些功能很简单的需求而设计的一句话函数 def calc(n): return n**n print(calc(10)) #换成匿名函数 calc = lambda n ...

  9. python 内置函数总结(大部分)

    python 内置函数大讲堂 python全栈开发,内置函数 1. 内置函数 python的内置函数截止到python版本3.6.2,现在python一共为我们提供了68个内置函数.它们就是pytho ...

随机推荐

  1. python之路day15--内置函数

    函数分为自定义函数和内置函数 python内置函数分类: 5.5.1 强制转换 int() / str() / bool() / list() / tuple() / dict() / set() 5 ...

  2. mysql分批导出数据和分批导入数据库

    mysql分批导出数据和分批导入数据库 由于某些原因,比如说测试环境有很多库,需要迁移到新的环境中,不需要导出系统库的数据.而数据库又有好多,如何才能将每个库导出到独立的文件中呢?导入到一个文件的话, ...

  3. CF1257E/F

    E 给出三个序列共n个元素,每个元素值为1~n且不重 一次可以把一个元素换到另一个序列中,求最少操作次数使得三个序列(可为空)分别排序后并在一起为1~n顺序 题解 (伪)神仙题 随便dp,依次考虑每个 ...

  4. linux lazarus 连接mssqlserver

    1 . 从https://www.freetds.org/ 下载驱动源文件 2. 参照 https://www.freetds.org/userguide/config.htm 内容编译 3. 启动l ...

  5. vue项目中监听sessionStorage值发生变化

    首先在main.js中给Vue.protorype注册一个全局方法, 其中,我们约定好了想要监听的sessionStorage的key值为’watchStorage’, 然后创建一个StorageEv ...

  6. JSP如何实现文件断点上传和断点下载?

    核心原理: 该项目核心就是文件分块上传.前后端要高度配合,需要双方约定好一些数据,才能完成大文件分块,我们在项目中要重点解决的以下问题. * 如何分片: * 如何合成一个文件: * 中断了从哪个分片开 ...

  7. CSS 阴影应用

    1.背景阴影的使用 box-shadow:1px 1px 1px 1px #ccccccc inset; 说明:第一个参数为水平阴影的大小.第二个为垂直阴影的大小(值可以为负数).第三个参数是阴影模糊 ...

  8. 安装浏览器的vue插件

    安装浏览器的vue插件步骤: 1.在浏览器中打开 https://github.com/vuejs/vue-devtools Clone or download  vue-devtools. 2.解压 ...

  9. 大数据笔记(二十五)——Scala函数式编程

    ===================== Scala函数式编程 ======================== 一.Scala中的函数 (*) 函数是Scala中的头等公民,就和数字一样,可以在变 ...

  10. [LeetCode]-algorithms-Reverse Integer

    Reverse digits of an integer. If the integer's last digit is 0, what should the output be? ie, cases ...