Home >Backend Development >Python Tutorial >What are the Differences Between Python's `eval`, `exec`, and `compile` Functions?
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 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 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 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
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!