Skip to main content

compile()

The compile() function in Python is a built-in function that is used to compile the source into a code or AST object. The function takes three arguments: source, filename, and mode. The source argument represents the source code to be compiled, the filename argument represents the file from which the code was read, and the mode argument specifies the compilation mode (eval, exec, or single). The compile() function returns a code object which can be executed using the exec() function.

Parameter Values

Parameter Description
source

A string containing the Python source code to compile.

filename

A file from which the code was read. If the code was not read from a file, it can be set to '<string>'.

mode

The mode in which the source should be compiled. Possible values are 'exec', 'eval', and 'single'.

Return Values

compile() return types are code objects in Python.

How to Use compile() in Python

Example 1:

The compile() function is used to compile source code into a code or AST object that can later be executed or evaluated dynamically.

code = 'print(123 + 456)' 
compiled_code = compile(code, 'example', 'exec') 
eval(compiled_code)
Example 2:

The compile() function can take a string, file, or AST object as input and return a code object for later execution.

with open('script.py', 'r') as file: 
    compiled_code = compile(file.read(), 'script.py', 'exec') 
exec(compiled_code)
Example 3:

The compile() function can handle different types of source code, such as single statements, modules, and functions.

def function(): 
    return 123 + 456 
compiled_function = compile('def function():\n    return 123 + 456', 'example', 'exec') 
eval(compiled_function)