The Python compile()
function is a built-in Python function that compiles a source ( normal string, byte string or an AST object) into a code or AST object.
So basically, compile()
function is used when you have Python source code in string form, and you want to make it into a Python code object that you can keep and use.
compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)
Once the source is compiled into code object by compile()
function, it can be executed by exec()
or eval()
.
compile()
function.exec
if the source consists of a sequence of statements, eval
if it consists of single expression where you can’t use series of the statement and single
if the source consists of a single interactive statement.0
and dont_inherit is -1
.Note: When compiling a string with multi-line code in ‘single
’ or ‘eval
’ mode, the input must be terminated by at least one newline character. This is to facilitate detection of incomplete and complete statements in the code module.
>>> code_object = compile('x=5+5','MyString','exec')
>>> exec(code_object)
>>> print (x)
10
>>> print(code_object)
<code object <module> at 0x0353E3E8, file "MyString", line 1>
As you can see in above example, first the object code_object
is converted into Python code object by compile()
function. Here the source is in the form of a simple string.
The returned code object is then executed using exec()
method. And the string source is executed assigning the sum of 5
and 5
to x
.
Also, you can see in the last line of code, that when we print the converted Python code object, the interpreter clearly indicates the type of code_object
as the code object. MyString
is the filename.
>>> code_object = compile('5+5','string','eval')
>>> eval(code_object)
10