compile()

Returns a runnable code object created from a string.

Syntax

compile(source, filename, mode)

Parameters

  • source: string or AST object
  • filename: The file from which the code is being read
  • mode:
    • eval: It accepts only a single expression.
    • exec: It can take a code block that has Python statements, class and functions, and so on.
    • single: It consists of a single interactive statement.
  • flags (optional) and dont_inherit (optional): Controls which future statements affect the compilation of the source. Default set to 0.
  • optimize (optional): The optimization level of the compiler. Default set to -1.

Example

Use compile() to take a code block and return a runnable code object.

x = compile('print(55)\nprint(88)', 'test', 'exec')
exec(x)

This will output:

55
88
Edit this page on GitHub

Contributors

Interested in helping build Docs? Read the Contribution Guide or share your feedback.

Learn Python on Codecademy

Edit this page on GitHub

Contributors