Home > Backend Development > Python Tutorial > How to use the eval function in Python

How to use the eval function in Python

爱喝马黛茶的安东尼
Release: 2019-07-25 13:43:01
Original
4832 people have browsed it

What is the eval function in Python? The actual parameter of eval(expression, globals=None, locals=None) is a string, and optional globals and locals. The globals argument must be a dictionary. locals can be any mapping object. The

How to use the eval function in Python

expression argument is parsed and evaluated as a Python expression (technically a list of conditions), using the globals and locals dictionaries for global and local namespaces . If the globals dictionary exists and does not contain a value keyed by __builtins__ , a reference to the dictionary keyed by builtins is inserted before expression is parsed. This means that expression usually has full access to standard builtins modules and the restricted environment is propagated. If the locals dictionary is omitted, its default value is the globals dictionary. If both dictionaries are omitted, the expression will be evaluated in the context in which eval() is called. The return value is the result of evaluating the expression. Syntax errors will be reported as exceptions.

Related recommendations: "Python Video Tutorial"

For example:

>>> x = 1
>>> eval('x+1')
2
Copy after login

This function can also be used to execute any code object (such as compile() created). In this case, the argument is a code object, not a string. If the mode argument when compiling the object is 'exec' then the return value of eval() is None .

Tips: The exec() function supports dynamic execution of statements. The globals() and locals() functions each return the current global and local dictionaries, so you can pass them to eval() or exec() for use.

The above is the detailed content of How to use the eval function in Python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template