exec, eval usages in Python _python

Source: Internet
Author: User

Exec can execute dynamic Python code, like the Eval function of JavaScript, and the eval function in Python can compute the Python expression and return the result (exec does not return the result, print (eval (...)) prints none);

Copy Code code as follows:

>>> EXEC ("Print (\" Hello, world\ ")")
Hello, world

>>> A = 1
>>> EXEC ("a = 2")
>>> A
2

Here is the concept of scope (namespace, scope), to create a new scope (a dictionary) to perform exec (JavaScript does not have this feature) in order not to break the current scope:

Copy Code code as follows:

>>> scope = {}
>>> EXEC ("a = 4", scope)
>>> A
2
>>> scope[' a ']
4

>>> Scope.keys ()
Dict_keys ([' A ', ' __builtins__ '])

__BUILTINS__ contains all the built-in functions and values;

and the normal {} does not contain __builtins__

Copy Code code as follows:

>>> a = {}
>>> A.keys ()
Dict_keys ([])

As with exec, Eval can also use namespaces:

Copy Code code as follows:

>>> result = eval (' 2+3 ')
>>> result
5
>>> scope={}
>>> scope[' a '] = 3
>>> scope[' b '] = 4
>>> result = eval (' a+b ', scope)
>>> result
7

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.