Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Scan for outdated or missing drivers - takes under a minute3Clear out junk files and repair common Windows errorsPython’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.
#1 Best Overall
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.
Rank #2
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.
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.
Best Value
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: removeassertstatements.optimize=2: removeassertstatements and docstrings.
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.
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.
Quick Recap
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.




