Python compile() function translates human-readable Python code (source code) into a format the computer can understand (bytecode). The Python interpreter then executes this bytecode. It’s particularly useful when you want to pre-compile code for faster execution or perform advanced operations on the code itself.
compile()
Syntax
code_object = compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)
code_object
: Stores the compiled bytecode, ready for execution.compile()
: The built-in Python function for compilationsource
: The Python code you want to compile (can be a string, bytes, or an AST object)filename
: A string representing the filename from which the code was read (useful for error messages).mode
: Specifies the type of code being compiled (‘exec’, ‘eval’, or ‘single’).flags
(optional): Control additional compilation optionsdont_inherit
(optional): Determines inheritance behavior for future exec callsoptimize
(optional): Sets the optimization level
Example 1: Python compile()
code = 'a = 5\nb = 10\nprint(a + b)'
compiled_code = compile(code, '<string>', 'exec')
exec(compiled_code) # Output: 15
Code Explanation
- Line 1: Defines a simple Python code snippet as a string
- Line 2: Compiles the code, specifying the filename as ‘<string>’ (since it’s not from a file) and the mode as ‘exec’ (to execute multiple statements)
- Line 3: Executes the compiled code, resulting in the output ’15’
Output
15
Example 2: Dynamic Code Generation with Python compile()
user_input = input("Enter a Python expression: ")
compiled_code = compile(user_input, '<string>', 'eval')
result = eval(compiled_code)
print(result)
Code Explanation
- Line 1: Prompts the user to enter a Python expression
- Line 2: Compiles the user’s input, using ‘eval’ mode for single expressions
- Line 3: Evaluates the compiled code, potentially performing calculations or other operations based on the user’s input
- Line 4: Prints the result of the evaluation