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
| Name | Description |
|---|---|
| source | Python source code as a string or AST object. |
| filename | A name used in error messages, often a descriptive placeholder. |
| mode | Use "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"])