October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk4 min

Python compile() Function: A Practical Guide

Python’s compile() turns source into a code object or AST without executing it. Learn which mode to choose, how flags work, and what to know before using exec() or eval().
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Python’s built-in compile() parses source and turns it into a reusable code object—or, with an AST option, an abstract syntax tree. It does not run the code object. Choose 'exec', 'eval', or 'single' according to the kind of source you have; execution, if appropriate, happens later with exec() or eval().

What does Python’s compile() function do?

compile() lets you compile source in memory rather than immediately running it. The result is normally a code object that Python can execute later. If you request AST-only output with compiler flags, it returns an abstract syntax tree instead. The documented Python 3.14 signature is:

compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)

Compilation can be useful when you need to validate syntax before execution, compile source once for repeated use, or separate the compilation stage from a later execution stage. A successful compile only means Python accepted the input under the chosen mode and compiler options; it does not show that running it will be safe or produce the result you intend.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose the right mode

The mode argument determines what form of Python source is accepted and what kind of code object is produced.

Mode Use it for Example source How to run the resulting code object
'exec' A statement or a suite of statements x = 2nprint(x) exec(code)
'eval' A single expression 1 + 2 eval(code)
'single' A single interactive statement 1 + 2 Run as interactive input; a non-None expression result is printed

Use 'exec' for code containing assignments, definitions, or multiple statements. Use 'eval' when the entire input must be one expression whose value you want back. 'single' follows interactive interpreter behavior, including printing a non-None expression result.

Compile first, then execute separately

Never treat compilation as a security filter. Python’s documentation warns: “This function executes arbitrary code. Calling it with untrusted user-supplied input will lead to security vulnerabilities.” That warning appears in the Python Software Foundation’s Python 3.14 built-in functions documentation under exec(). Compiling untrusted input does not make it safe to execute, and changing __builtins__ is not a security mechanism.

Expression example with eval()

This example uses a fixed, trusted expression. The first line compiles it; the second evaluates the code object and returns its value.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

code = compile("1 + 2", "<string>", "eval")
result = eval(code)
print(result) # 3

Statement example with exec()

This example compiles a fixed statement suite and executes it in a separate step:

code = compile("total = 2 + 3nprint(total)", "<string>", "exec")
exec(code)

Only use exec() or eval() on source you trust or have safely constrained by a design that does not rely on compilation as protection.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What the arguments control

Argument Meaning
source A string, byte string, or AST object to compile.
filename A source label used in diagnostics. Use a real or meaningful filename for file-associated or generated code; '<string>' is a conventional label when there is no file.
mode 'exec' for statements, 'eval' for one expression, or 'single' for one interactive statement.
flags Bitwise-combinable compiler options and future-feature flags.
dont_inherit When false, compiler options and future statements in the surrounding code may apply along with explicit flags. When nonzero, only the explicit flags apply.
optimize Controls optimization level; -1 follows the interpreter setting, while 0, 1, and 2 specify documented levels.

Compiler flags and future features

Compiler flags can enable options such as parsing source into an AST rather than producing executable code. Future-feature flags can be obtained from the relevant feature objects in __future__; AST compiler flags are available in the ast module. Prefer those named values over unexplained hard-coded integers. With the default dont_inherit=False, flags and future statements in the surrounding code can affect compilation. Set dont_inherit to a nonzero value when compilation should use only the flags passed explicitly.

Optimization levels

  • optimize=-1: follow the interpreter’s optimization setting.
  • optimize=0: retain assertions and docstrings.
  • optimize=1: remove assert statements.
  • optimize=2: remove assert statements and docstrings.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

When to use compile(), AST tools, or bytecode utilities

Need Appropriate tool What it returns or does
Compile a statement suite in memory compile(source, filename, 'exec') Returns a code object; execute separately with exec().
Compile one expression in memory compile(source, filename, 'eval') Returns a code object; evaluate separately with eval().
Compile one interactive statement compile(source, filename, 'single') Returns a code object with interactive result-printing behavior.
Inspect or transform syntax structure ast.parse() or AST compiler flags Produces syntax structure for analysis or transformation rather than an ordinary executable code object.
Write a bytecode cache for one source file py_compile Creates a .pyc cache file; see the py_compile documentation.
Compile source files across directories compileall Provides directory-oriented compilation utilities; see the compileall documentation.

The built-in function’s in-memory result is different from writing cached bytecode to disk. Choose py_compile for a single file’s cache workflow or compileall for a directory-oriented workflow.

Errors and practical limits

Invalid source can raise SyntaxError, including source with a null character or undecodable input. The Python 3.14 documentation also lists ValueError for invalid modes or flags and surrogate characters in string source, MemoryError or RecursionError for overly complex input, and OverflowError for input that is too large. Exact edge behavior can vary by Python release.

The CPython documentation cautions that sufficiently large or complex input compiled to an AST may crash the interpreter because of AST compiler stack-depth limitations. Do not use extreme inputs to probe that limit.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Python version scope

The signature and behavior described here follow the Python 3.14 documentation. CPython’s main-branch documentation describes a future module parameter as added in Python 3.15; it is not part of the Python 3.14 signature covered above. Check the documentation for the specific interpreter version you deploy when relying on version-sensitive options. See the CPython built-in functions documentation.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

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

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.