Facebook Page Twitter Page LinkedIn Page
× Python Tutorial Python Advanced Python Resources Python Libraries


The Python compile() function is used to return the specified source as code object which can be executed.

Syntax

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

Parameters

No parameter is required.

source Required. Specify the source to compile. It can be a String, a Bytes object, or an AST object.
filename Required. Specify the name of the file from which code was read. If it is not read from a file, any name can be given.
mode Required. Specify mode. It can take following values:
  • eval : accepts a single expression.
  • exec : if the source is a block of statement.
  • single : if the source is single inter.
flag Optional. Specify how to compile the source. Default: 0.
dont_inherit Optional. Specify how to compile the source. Default: False.
optimize Optional. Specify optimization level of the compiler. Default: -1.

Example: Using compile() function

In the below example, compile() function is used to return the string source as code object. As the source contains block of statement, therefore 'exec' mode is used to create code object. Finally, the code object is executed using exec function.

SourceInString = "a=10\nb=15\nprint('a + b =', (a+b))"
CodeObject = compile(SourceInString, 'code', 'exec')
exec(CodeObject)

The output of the above code will be:

a + b = 25

❮ Python Built-in Functions