Yandex

Python compile() Function – Compile Source Code at Runtime



Python compile() Function

The compile() function in Python is used to compile source code into a code object that can be executed using the exec() or eval() functions.

This is especially useful when you want to execute Python code that is available as a string.

Syntax

compile(source, filename, mode)

Parameters:

  • source: A string or AST object containing valid Python code.
  • filename: A name string (usually '<string>' if reading from a string).
  • mode: One of 'exec', 'eval', or 'single'.

Returns:

  • A code object which can be passed to exec() or eval().

Modes Explained

  • 'exec': For statements (like loops, function definitions).
  • 'eval': For expressions (like 2 + 2).
  • 'single': For a single interactive statement (like in the REPL).

Example 1: Using compile() with 'eval'

code = "3 + 5"
compiled_code = compile(code, "", "eval")
result = eval(compiled_code)
print(result)
8

Example 2: Using compile() with 'exec'

code = """
for i in range(3):
    print("Line", i)
"""
compiled = compile(code, "", "exec")
exec(compiled)
Line 0
Line 1
Line 2

Example 3: Using compile() with 'single'

code = "print('Hello')"
compiled = compile(code, "", "single")
exec(compiled)
Hello

Use Cases

  • Dynamically executing user-generated Python code.
  • Building a code editor, REPL, or interactive shell.
  • Converting strings into executable logic.

Common Mistakes

  • Using 'eval' for code that includes statements like if or for will raise a SyntaxError.
  • Always validate untrusted code before executing.

Interview Tip

In advanced interviews or coding tools, compile() is used to simulate a mini Python interpreter. It shows your understanding of dynamic code execution.

Summary

  • compile() turns code strings into code objects.
  • Use eval() or exec() to run the compiled code.
  • Modes: 'exec' (statements), 'eval' (expressions), 'single' (REPL).

Practice Problem

Write a program that reads an arithmetic expression from the user, compiles it, and evaluates the result.

user_input = input("Enter an arithmetic expression: ")
code_obj = compile(user_input, "", "eval")
result = eval(code_obj)
print("Result:", result)


Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M