Python Tutorial Python Advanced Python References Python Libraries

Python compile() Function



The Python compile() function returns 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 example below, compile() function returns 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

5