CKTIS / Python
compile()
Compiles source text into a reusable code object for the selected compilation mode.
Version: Python 3.14; repository image, production runtime not attested
Syntax
compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)Compiles source text into a reusable code object for the selected compilation mode.
An assignment statement using = needs a statement mode. A parenthesized assignment expression using := is valid in expression mode. The filename labels diagnostics.
Compiles text, bytes or an AST for a selected mode. eval expects an expression, exec a suite of statements and single an interactive statement. The filename identifies diagnostics. The compiled multiplication evaluates to 28; putting ordinary assignment in eval mode instead raises SyntaxError before any execution. The expression (x := 4) compiles in eval mode and yields 4. With PyCF_ONLY_AST the return is an AST.
code = compile("x + 1", "<calc>", "eval")
assert code.co_filename == "<calc>" and eval(code, {"x": 3}) == 4
assert eval(code, {"x": 9}) == 10
Examples
expression = compile("4 * 7", "<example>", "eval")
print(eval(expression))
try:
compile("x = 4", "<example>", "eval")
except SyntaxError as error:
print(type(error).__name__)
Result
28 SyntaxError
Compiles text, bytes or an AST for a selected mode. eval expects an expression, exec a suite of statements and single an interactive statement. The filename identifies diagnostics. The compiled multiplication evaluates to 28; putting ordinary assignment in eval mode instead raises SyntaxError before any execution. The expression (x := 4) compiles in eval mode and yields 4. With PyCF_ONLY_AST the return is an AST.