Python compile() Function

The compile() converts a string to a Python code object. The code object is then executed using exec() function.

Compile source into a code object that can be executed by exec() or eval().

Syntax

Python
compile(source, filename, mode, flags, dont_inherit, optimize, *, _feature_version: int = ...) -> Any

Parameters

ParameterDescription
source. Required. The string (or byte string) containing the code to compile, or an AST object containing the code.
filename Required. The name of the source file for this code, or any name you wish if the code did not come from a file.
mode Optional. The manner in which the code will be compiled. Accepted values are:
  • 'eval' - source consists of only a single expression.
  • 'exec' - source contains Python statements, class and functions: a full program, in other words.
  • 'single' - source consists of a single interactive statement
flags Optional. controls which compiler flags are enabled. Default Value: 0.
dont_inherit Optional. controls which future features are enabled. Default Value: 0.
optimize:int Optional. optimization level of the compiler. Default value -1.

The code string, source filename or just a name, and the code type ('exec', 'eval', or 'single') must be specified.

Example

Python
# A code block to be executed:
codeString = 'a = 5\nb = 6\nprint(f"{a} + {b} = {a + b}")'
codeObject = compile(codeString, 'add', 'exec')
exec(codeObject)

# An expression to be evaluated:
codeString = 'print(3 + 11)'
codeObject = compile(codeString, 'add', 'eval')
exec(codeObject)

# An "interactive" statement that will be printed
codeString = '7 * 3'
codeObject = compile(codeString, 'add', 'single')
exec(codeObject)

Output

5 + 6 = 11
14
21

Notes

If variables are assigned in the code string, those variables are available after the code has been executed. This only works with the 'exec' code type.

Example

Python
# Assign a value to a variable in the code string 
codeString = 'a = 3\nb = 4\nmySum = a + b'
codeObject = compile(codeString, 'add', 'exec')
exec(codeObject)
# We can now use the variables a, b, and mySum
print(f'{a} + {b} = {mySum}')

Output

3 + 4 = 7

You can also reference variables defined outside of the code string.

Example

Python
# Using a variable defined outside the code string
n = 31.006
codeString = 'cubeRoot = n ** (1./3)'
cubeRootFnc = compile(codeString, 'cubeRoot', 'exec')
exec(cubeRootFnc)
print(f'The cube root of {n} is {cubeRoot}')

Output

The cube root of 31.006 is 3.141583309036842