compile() Compile source to code object
Last updated: 2026-09-22
compile() Compile source to code object
compile() compiles source string into a code object that can be executed by exec() / eval().
| Category | Built-in Functions |
|---|---|
| Kind | Built-in Function |
| Python Version | all |
📝 Syntax
compile(source, filename, mode)
⚙️ Parameters
| source Required | Source code: a string, bytes, or AST object. |
|---|---|
| filename Required | Filename shown in error messages; pass ' |
| mode Required | Compilation mode: 'exec', 'eval', or 'single'. |
| flags Optional | Compiler flags, e.g. ast.PyCF_ONLY_AST.(Default:0) |
| dont_inherit Optional | Whether to ignore surrounding compile flags.(Default:False) |
| optimize Optional | Optimization level; -1 uses the interpreter's setting.(Default:-1) |
Returns:A code object executable by exec() / eval().
💥 Raises
SyntaxError— Raised when the source has a syntax error.ValueError— Raised when mode is invalid or the source contains null bytes.TypeError— Raised when source or mode has an invalid type.
▶ Example
Edit the code, press Run, and see the result in the output panel:
Output:
3
🏷️ Related Built-in Functions
💡 Related Cases
More case studies coming soon — check back later.
❓ FAQ
QWhat is the difference between the three modes of compile()?
A'exec' compiles a statement block (if, def, for, etc.), 'eval' compiles a single expression (which can be evaluated to a value), and 'single' compiles a single interactive statement and will print expression results.
QWhat should I pass for the filename argument?
AFor dynamically generated inline code, the convention is to pass ''. It only appears in error messages (the traceback) and has nothing to do with a real file — it never actually reads one.
QAfter compile(), how do I execute the result?
APass the returned code object to exec(code) or eval(code): code compiled in 'exec' mode is run with exec, 'eval' mode with eval.
QWhat happens if the source has a syntax error?
AA SyntaxError is raised at the compile() stage — earlier than executing the string directly, which is ideal for 'compile first, execute later' scenarios.