Built-in Functions and Types
compile()
Translate source text, bytes or an AST into a code object, or request an AST using compiler flags. Compilation checks syntax and creates an executable representation without running its statements. Select eval for a single expression, exec for statements, or single for interactive input. SyntaxError indicates invalid syntax; invalid option values may raise ValueError. Use a descriptive filename for diagnostics.
Formal Syntax & Structure
python syntaxpython
compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| source | str | bytes | AST | Source or syntax tree to compile. |
| filename | str | Diagnostic label; need not name an existing file. |
| mode | str | eval, exec or single. |
| flags | int | Compiler flag bitmask; default 0. |
| dont_inherit | bool | If true, do not inherit compiler flags from the caller. |
| optimize | int | -1 uses interpreter settings; 0 normal, 1 removes asserts, 2 also removes docstrings. |
Return Value
code object | AST
Compiled representation; AST-only flags can request a syntax tree.
Working Example
Example Snippetpython
# Local trusted-source demonstration; no dynamic input.code = compile("price * 2", "<pricing-example>", "eval")print(code.co_filename)print(code.co_names)try: compile("value =", "<invalid-example>", "exec")except SyntaxError: print("invalid syntax")