Python compile() functie

Example

Compile de tekst naar code en voer vervolgens uit:

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

Run Example

Definition and Usage

The compile() function returns the specified source as a code object and prepares it for execution.

Syntax

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

Parameter Value

Parameter Description
source Required. The resource to be compiled, which can be a string, bytes, or AST object.
filename Required. The name of the file from which the source comes. If the source is not from a file, you can write anything.
mode

Required. Valid 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. How to compile the source. The default is 0.
dont-inherit Optional. How to compile the source. The default is False.
optimize Optional. Define the optimization level of the compiler. The default is -1.

More Examples

Example

Compile and execute one or more statements:

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

Run Example

Related Pages

Reference Manual:eval() Function

Reference Manual:exec() Function