Skip to content

Python compile() Function

How to use Python's compile() function to convert source code (strings, bytes, or AST objects) into executable code objects for later use with exec() or eval().

The compile() function computes the Python code from a source object and returns it.

Syntax

compile(source, filename, mode, flag, dont_inherit, optimize)

compile() Parameters

Python compile() function parameters:

Parameter Condition Description
source Required Specify the source to compile, can be a String, a Bytes object, or an AST object
filename Required Specify the name of the file that the source comes from. If the source does not come from a file, you can write whatever you like
mode Required Legal values:
- eval: if the source is a single expression
- exec: if the source is a block of statements
- single: if the source is a single interactive statement
flags Optional Specify how to compile the source. Default value is 0
dont-inherit Optional Specify how to compile the source. Default value is False
optimize Optional Optional. Defines the optimization level of the compiler. Default value is -1

compile() Return Value

Python compile() function returns the specified source as a code object, ready to be executed.

Examples

Example 1: compile text as code and execute it

Compile text as code, and then execute it.

x = compile('print(55)', 'test', 'eval')
exec(x)

output:

55

Example 2: compile text as code and execute it

codeInString = 'a = 5\nb=10\nmul=a*b\nprint("mul =",mul)'
codeObject = compile(codeInString, 'multiplyNumbers', 'exec')
exec(codeObject)

output

mul = 50
Navigation