compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)

Compiles source code into a code object or an AST (Abstract Syntax Tree) object. The code object can be executed using eval or exec.

Parameters

  • source: A string, byte sequence, or AST object.
  • filename: The file from which the code was read. If not from a file, use "<string>".
  • mode: Determines the type of code to compile. Use "exec" for a sequence of statements, "single" for a single statement, and "eval" for a single expression.
  • Optional parameters flags and dont_inherit: Specify compiler options and __future__ statements. If not specified or zero, the code uses the same flags as the calling code.
  • optimize: Specifies the optimization level. -1 uses the interpreter’s optimization level set by -O options. 0 means no optimization, 1 removes assert statements, and 2 also removes docstrings.

Return Value

The compile() function returns a Python code object.

Examples

compiled = compile('print("Hello")', '<string>', 'exec')
exec(compiled)