Python compile() Function
Description
The compile() function compiles a string into byte code.
Syntax
The syntax of the compile() method is as follows:
compile(source, filename, mode[, flags[, dont_inherit]])
Parameters
- source -- a string or an 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 exec, eval, or single.
- flags -- the variable scope and local namespace; if provided, it can be any mapping object.
- flags and dont_inherit are used to control the flags when compiling source code
Return Value
Returns the result of expression execution.
Example
The following examples show 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
0
x10141e0b0
,
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 built-in function