Python compile() Function

Python 内置函数Python Built-in Functions


Description

The compile() function compiles a string into byte code.

Syntax

The following is the syntax of the compile() method:

compile(source, filename, mode[, flags[, dont_inherit]])

Parameters

  • source -- A string or AST (Abstract Syntax Trees) object.
  • filename -- The name of the code file. If the code is not read from a file, pass some recognizable value.
  • mode -- Specifies the kind of code to compile. It can be specified as exec, eval, single.
  • flags -- Variable scope, local namespace; if provided, it can be any mapping object.
  • flags and dont_inherit are flags used to control the compilation of source code.

Return Value

Returns the execution result of the expression.


Examples

The following example demonstrates the use of the compile function:

>>>str = "for i in range(0,10): print(i)" >>> c = compile(str,'','exec') # Compile into a byte code object >>> c <code object <module> at 0x10141e0b0, file "", line 1> >>> exec(c) 0 1 2 3 4 5 6 7 8 9 >>> str = "3 * 4 + 5" >>> a = compile(str,'','eval') >>> eval(a) 17

Python 内置函数Python Built-in Functions

Other Extensions