Skip to content
Built-in Functions

compile()

Turn source code text into a code object.

compile(source, filename, mode)

compile() prepares Python source stored in a string for eval() or exec(). Most beginners can write code directly, but compilation is useful when code starts as text.

Parameters

NameDescription
sourcePython source code as a string or AST object.
filenameA name used in error messages, often a descriptive placeholder.
modeUse "eval", "exec", or "single" depending on the source.

Returns

A code object that can be evaluated or executed.

Try it

Run it and change it
source = "total = 2 + 3"
code = compile(source, "<string>", "exec")
scope = {}
exec(code, scope)
print(scope["total"])

Related entries