Python compile() Function: Learn to Compile Python Code | Syntax, Examples & Use Cases

Introduction: Python compile() Function

When working with Python, there are situations where code is available as a string instead of being written directly inside a program. Whether you’re building interactive applications, creating scripting tools, or executing dynamically generated code, Python first needs to convert that code into a format it can execute.

Without a built-in solution, handling dynamically generated Python code would be much more difficult, especially when working with functions like exec() and eval().

A simple solution to these situations is the Python compile() Function.

What it is: The compile() function is a built-in Python function that converts source code into a code object. The compiled code object can later be executed using functions such as exec() or evaluated using eval().

Take a look at a quick example to see how it works.

You can also explore its real-world use cases to learn where it is commonly used.

Now let’s explore its syntax, parameters, return value, and practical examples.

💡 Tip: Looking for more built-in functions? Visit the Python Built-in Functions Learning Guide for simple explanations, practical examples, and step-by-step tutorials.

Syntax, Parameters, Return Value and Examples: Python compile() Function

The following section explains the syntax, parameters, return value, and a quick example of the Python compile() Function.

Syntax

compile(source, filename, mode)

Parameters

Parameter Description
source The Python source code to compile. It can be a string, bytes, or an abstract syntax tree (AST).
filename The filename associated with the compiled code. Use a descriptive name or "<string>" when compiling code from a string.
mode Specifies how the code will be compiled. Valid values are "exec", "eval", and "single".

Return Value

Return Value Description
code Returns a compiled code object that can be executed or evaluated later.

Quick Example

The following example compiles and executes a simple Python statement:

source = "print('Hello, Python!')"

code = compile(source, "<string>", "exec")

exec(code)

# Output:
Hello, Python!

The compile() function converts the source code into a code object. The exec() function then executes that compiled code.

How the Python compile() Function Works

  • The compile() function converts source code into a code object.
  • The source code can be provided as a string or similar supported object.
  • The mode determines how the code will be compiled.
  • The returned code object can be executed using exec() or evaluated using eval().
  • If the source code contains syntax errors, Python raises a SyntaxError.

Examples: Python compile() Function

The following examples show how the Python compile() Function works in different programming scenarios.

Example 1: Compiling and Executing Python Code

source = "print('Welcome to Python')"

code = compile(source, "<string>", "exec")

exec(code)

# Output:
Welcome to Python

Explanation: The compile() function first converts the source code into a code object. The exec() function then executes the compiled code and displays the output.

Example 2: Compiling an Expression with eval Mode

expression = "25 + 15"

code = compile(expression, "<string>", "eval")

result = eval(code)

print(result)

# Output:
40

Explanation: The "eval" mode is designed for expressions that produce a value. After compilation, eval() evaluates the code object and returns the result.

Example 3: Compiling a Single Interactive Statement

source = "print('Hello')"

code = compile(source, "<string>", "single")

exec(code)

# Output:
Hello

Explanation: The "single" mode is mainly intended for interactive Python sessions. It compiles one statement at a time before execution.

Example 4: Compiling Multiple Statements

source = """
x = 10
y = 20
print(x + y)
"""

code = compile(source, "<string>", "exec")

exec(code)

# Output:
30

Explanation: Unlike "eval", the "exec" mode can compile multiple Python statements together. This makes it useful when executing blocks of dynamically generated code.

Example 5: Reusing Compiled Code

source = "print('Compiled once, executed many times')"

code = compile(source, "<string>", "exec")

exec(code)
exec(code)

# Output:
Compiled once, executed many times
Compiled once, executed many times

Explanation: Once a code object has been created, it can be executed multiple times without compiling the source code again. This avoids repeated compilation.

Example 6: Compiling a Mathematical Formula

formula = "(12 * 5) - 18"

code = compile(formula, "<string>", "eval")

print(eval(code))

# Output:
42

Explanation: This example shows that the Python compile() Function is not limited to simple values. Entire expressions can be compiled and evaluated whenever required.

Example 7: Handling Invalid Python Code

try:
    source = "for"
    code = compile(source, "<string>", "exec")
except SyntaxError as e:
    print(e)

# Output:
invalid syntax (<string>, line 1)

Explanation: If the supplied source code is not valid Python syntax, the compile() function raises a SyntaxError. In this example, the exception is handled using a try-except block so the program terminates gracefully.

Use Cases: When to use the compile() Function

Below are some common situations where the Python compile() Function becomes useful:

  • Executing dynamically generated Python code.
  • Working with exec() and eval().
  • Building scripting engines and interpreters.
  • Compiling expressions before repeated execution.
  • Creating interactive programming tools.
  • Processing user-generated Python code.

Key Takeaways: compile() Function

Before wrapping up, here are the key points to remember about the Python compile() Function:

  • The compile() function converts source code into a code object.
  • It accepts the source code, filename, and compilation mode.
  • The supported modes are "exec", "eval", and "single".
  • The returned code object can be executed using exec() or evaluated using eval().
  • Compiled code can be reused multiple times.
  • Invalid source code raises a SyntaxError.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top