Python compile()
: Convert Code into Executable Form
The compile()
function translates Python code (string, file, or AST) into bytecode, which can then be executed using exec()
or eval()
. This is useful for dynamic code execution, working with files, and optimizing performance.
Simple Example
code = "print('Hello, World!')"
compiled_code = compile(code, "", "exec")
exec(compiled_code)
# Output: Hello, World!
Here, compile()
converts the string into executable bytecode, which is then run using exec()
.
Syntax
compile(source, filename, mode)
- source → Code as a string, file, or AST (Abstract Syntax Tree).
- filename → Name of the file or
<string>
if it’s from a variable. - mode →
"exec"
for multiple lines,"eval"
for a single expression,"single"
for a single statement.
1. Using compile()
with eval()
for Expression Execution
compile()
can be used with eval()
when dealing with expressions that return a value.
code = "5 + 10"
compiled_code = compile(code, "", "eval")
result = eval(compiled_code)
print(result) # Output: 15
Great for calculating dynamic expressions at runtime.
2. Executing Multiple Lines of Code
If you need to run multiple lines, use "exec"
.
code = """
x = 5
y = 10
print(x + y)
"""
compiled_code = compile(code, "", "exec")
exec(compiled_code)
# Output: 15
This is helpful when running dynamically generated scripts.
3. Reading and Running Python Code from a File
You can load and execute Python code from a file using compile()
.
with open("script.py", "r") as f:
code = f.read()
compiled_code = compile(code, "script.py", "exec")
exec(compiled_code)
Useful when loading and executing external scripts dynamically.
4. Securing eval()
with compile()
(Restricted Scope Execution)
When using eval()
, you can limit what variables it has access to.
code = "x + y"
compiled_code = compile(code, "", "eval")
safe_scope = {"x": 10, "y": 5}
print(eval(compiled_code, {}, safe_scope)) # Output: 15
This helps prevent security risks by controlling variable access.
Key Notes
- ✔ Converts Python code into bytecode – allows execution of dynamic code.
- ✔ Works with
exec()
andeval()
– use for scripts or expressions. - ✔ Useful for loading code from files – great for dynamically running scripts.
- ✔ Can restrict variable scope – improves security when evaluating code.
By using compile()
, you can execute dynamic code safely and efficiently, making it a powerful tool for scripting, automation, and runtime execution. 🚀