Python compile() Built in Function
The Python compile() function is a built-in function that returns a code object from a source string or an AST object. A code object is an internal representation of Python code that can be executed by the exec() or eval() functions.
The compile() function takes three mandatory parameters: source, filename and mode. The source can be a string or an AST object containing Python code. The filename can be any string indicating where the code came from. The mode can be either ‘exec’, ‘eval’ or ‘single’ depending on what kind of code you want to compile.
Here are some examples of using the compile() function:
# Example 1: Compile and execute a simple statement
x = compile('print(55)', 'test', 'exec')
exec(x) # 55
# Example 2: Compile and execute multiple statements
y = compile('a = 8\nb = 7\nsum = a + b\nprint("sum =", sum)', 'test', 'exec')
exec(y) # sum = 15
# Example 3: Compile and evaluate an expression
z = compile('3 * 4 + 5', 'test', 'eval')
eval(z) # 17
# Example 4: Compile and execute a single interactive statement
w = compile('name = input("Enter your name: ")', 'test', 'single')
exec(w) # Enter your name: Alice
If you have any questions about this code, you can drop a line in comment.
Comments
Post a Comment