compile()
The built-in compile()
function converts a string containing Python code into a code object. This code can be executed using exec()
or eval()
. This allows for the dynamic execution of Python code stored in strings:
>>> code = compile("print('Hello, World!')", "<string>", "exec")
>>> exec(code)
Hello, World!
compile()
Signature
compile(
source,
filename,
mode,
flags=0,
dont_inherit=False,
optimize=-1
)
Arguments
Argument | Description | Default Value |
---|---|---|
source |
The source code to compile. It can be a string, byte string, or an AST (abstract syntax tree) object. | Required argument |
filename |
The name of the file from which the code was read. Use "<string>" for code in a string. |
Required argument |
mode |
Specifies the type of code to compile: "exec" , "eval" , or "single" . |
Required argument |
flags |
Compiler options to activate. | 0 |
dont_inherit |
Controls whether to inherit future statements. | False |
optimize |
Optimization level of the compiler. | -1 |
Return Value
- Returns a code object that can be executed using
exec()
or evaluated witheval()
.
compile()
Examples
With an input expression and eval()
to evaluate it:
>>> code = compile("5 + 4", "<string>", "eval")
>>> eval(code)
9
With a string containing code and calling exec()
to run it:
>>> input_string = """
... def greet(name):
... return f"Hello, {name}!"
...
... print(greet("Jane"))
... """
>>> code = compile(input_string, "<string>", "exec")
>>> exec(code)
Hello, Jane!
compile()
Common Use Cases
The most common use cases for the compile()
function include:
- Precompiling expressions or scripts for repeated execution to improve performance
- Dynamically executing code received from an external source
- Evaluating mathematical expressions or other code snippets stored as strings
Note: The compile()
function is a powerful tool that allows you to compile arbitrary Python code that comes to you as strings. To run the resulting code, you can use eval()
or exec()
, which you must use with extreme care and caution, especially in those cases where the code comes from untrusted sources.
compile()
Real-World Example
Say that you want to evaluate mathematical expressions stored as strings. Using compile()
, you can precompile these expressions and evaluate them multiple times efficiently:
>>> import math
>>> expressions = ["3 + 5", "12 / 4", "math.sin(math.pi / 2)"]
>>> compiled_expressions = [
... compile(expr, "<string>", "eval") for expr in expressions
... ]
>>> results = [eval(code) for code in compiled_expressions]
>>> results
[8, 3.0, 1.0]
In this example, compile()
allows you to prepare expressions for evaluation just once, saving time when evaluating them repeatedly.
Related Resources
Tutorial
Python's exec(): Execute Dynamically Generated Code
In this tutorial, you'll learn how to use Python's built-in exec() function to execute code that comes as either a string or a compiled code object.
For additional information on related topics, take a look at the following resources: