Python built-in functions (19) -- eval, python built-in function eval

Source: Internet
Author: User

Python built-in functions (19) -- eval, python built-in function eval

English document:

eval( Expression, Globals = None, Locals = None)
The arguments are a string and optional globals and locals. If provided, GlobalsMust be a dictionary. If provided, LocalsCan be any mapping object.
The ExpressionArgument is parsed and evaluated as a Python expression (technically speaking, a condition list) using GlobalsAnd LocalsDictionaries as global and local namespace. If GlobalsDictionary is present and lacks '_ builtins _', the current globals are copied GlobalsBefore ExpressionIs parsed. This means that ExpressionNormally has full access to the standard builtinsModule and restricted environments are propagated. If LocalsDictionary is omitted it defaults to GlobalsDictionary. 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 createdcompile()). In this case pass a code object instead of a string. If the code object has been compiled'exec'AsModeArgument,eval()'S return value will beNone.

Hints: dynamic execution of statements is supported by exec()Function. globals()And locals()Functions returns the current global and local dictionary, respectively, which may be useful to pass around for use eval()Or exec().
See ast.literal_eval()For a function that can safely evaluate strings with expressions containing only literals.
Note:
  
1. Execute a dynamic statement and return the statement execution value.
>>> eval('1+2+3+4')10

2. The first parameter is the statement string. The globals parameter and locals parameter are optional parameters. If provided, the globals parameter must be a dictionary and the locals parameter is a mapping object.

>>> G = {'num': 2 }>>> eval ('num + 2') # num undefined 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) # defines num in g. You can execute 4

4. The locals parameter is used to specify the local variables that can be used during code execution and to collect the local variables after code execution.

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

5. To ensure successful code running, the globals parameter dictionary does not contain_ Builtins __Python automatically adds a key_ Builtins __Value is the reference of the builtins module. If you want to restrict the code from using the builtins module, you must add a key in global_ Builtins __, the value is {} (few do this ).

>>> G ={}>> eval ('abs (-1) ', g) 1 >>>> g = {' _ builtins __': {}}>> eval ('abs (-1) ', g) # You cannot use the built-in function 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

6. If the globals parameter is not provided, Python uses the dictionary returned by the globals () function by default. If the locals parameter is not provided, the globals parameter is used by default.

>>> Num = 1 >>> eval ('num + 2') 3 >>> globals () # return the key {'_ doc _': None, 'num': 1, '_ package _': None, '_ name _': '_ main _', '_ loader _': <class '_ frozen_importlib.BuiltinImporter'>, '_ spec __': none, '_ builtins _': <module 'builtins '(built-in) >}> eval ('num + 2 ',{}) # The locals parameter is not provided. The locals parameter = globals parameter 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) # The locals parameter contains the key of num, parameter Value: 3 >>> locals () {'_ doc _': None, 'L ':{...}, 'num': 1, '_ package _': None, '_ name _': '_ main _', '_ loader __': <class '_ frozen_importlib.BuiltinImporter'>, '_ spec _': None, '_ builtins __': <module 'builtins '(built-in) >}>>

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.