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:

Python
>>> code = compile("print('Hello, World!')", "<string>", "exec")
>>> exec(code)
Hello, World!

compile() Signature

Python Syntax
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 with eval().

compile() Examples

With an input expression and eval() to evaluate it:

Python
>>> code = compile("5 + 4", "<string>", "eval")
>>> eval(code)
9

With a string containing code and calling exec() to run it:

Python
>>> 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

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:

Python
>>> 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.

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.

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Nov. 21, 2024 • Reviewed by Dan Bader