Home >Backend Development >Python Tutorial >What are the Differences Between Python's `eval`, `exec`, and `compile` Functions?

What are the Differences Between Python's `eval`, `exec`, and `compile` Functions?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-11 18:17:10639browse

What are the Differences Between Python's `eval`, `exec`, and `compile` Functions?

The Difference Between eval, exec, and compile

Introduction

Python provides three powerful tools for executing code dynamically: eval, exec, and compile. Each serves a specific purpose, and it's important to understand their differences.

eval

Eval is used to evaluate a single expression. It takes a string representing the expression and returns its value. For example:

a = 5
result = eval('a + 10')
print(result)  # Output: 15

exec

Exec is used to execute a block of code. It takes a string representing the code and returns None. For example:

my_code = """
for i in range(5):
    print(i)
"""

exec(my_code)
# Output:
# 0
# 1
# 2
# 3
# 4

compile

Compile is used to compile code into bytecode, which can then be executed by the interpreter. It takes a string representing the code and a mode ('eval', 'exec', or 'single').

In 'eval' mode, compile compiles a single expression into bytecode that returns the expression's value. In 'exec' mode, it compiles a block of code into bytecode that returns None. In 'single' mode, it compiles a single statement or expression into bytecode that prints the repr of the expression's value.

For example:

bytecode = compile('a + 10', 'my_code', 'eval')
result = eval(bytecode)
print(result)  # Output: 15

bytecode = compile("""
for i in range(5):
    print(i)
""", 'my_code', 'exec')
exec(bytecode)
# Output:
# 0
# 1
# 2
# 3
# 4

Summary

Function What it does
eval Evaluates a single expression
exec Executes a block of code
compile Compiles code into bytecode

The above is the detailed content of What are the Differences Between Python's `eval`, `exec`, and `compile` Functions?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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