Python compile() built-in function
From the Python 3 documentation
Introduction
The compile()
function in Python is a built-in function that is used to convert a string or an Abstract Syntax Tree (AST) object into a code object. This code object can then be executed by functions like exec() or eval().
Example
Here’s a basic example of how it works:
code_string = """
def hello_world():
print('Hello, world!')
hello_world()
"""
# Compile the string into a code object
# The mode 'exec' is used for a sequence of statements.
# The mode 'eval' is for a single expression.
# The mode 'single' is for a single interactive statement.
code_object = compile(code_string, '<string>', 'exec')
# Execute the code object
exec(code_object)
# Output:
# Hello, world!