all Python 3Built-in functionsterm
compile
execution
Compiles a string or an AST into a code object. Used with exec() or eval() to run code built at runtime.
Syntax
compile(source, filename, mode)
The mode argument must match what you actually pass: 'eval' takes exactly one expression (a string containing an assignment raises SyntaxError right away), 'exec' takes any sequence of statements, 'single' takes one statement and echoes its result like the interactive shell. The filename argument is never opened — it is only a label that shows up in tracebacks and debuggers, so something descriptive like '<user-formula>' pays off when errors appear. The point of compiling separately is to parse the source once and reuse the code object in a loop; it adds no safety whatsoever, since the dangerous step is still the exec/eval call.
Examples
code = compile('1+2', '<string>', 'eval')
print(eval(code)) # → 3
stmt = compile('x=5\nprint(x)', '<s>', 'exec')
exec(stmt) # → 5
code2 = compile('[x**2 for x in range(5)]','<s>','eval')
print(eval(code2)) # → [0,1,4,9,16]
print(type(code)) # → <class 'code'>
See also
Open in the full glossarydocs.python.orgReport an inaccuracy