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.
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.
Python compile() Syntax
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
Python compile() Parameters
- source: It can be a normal string, byte string or an AST object. This must be supplied to the function.
- filename: Filename is the name of the file from which the code was read. You can pass any recognizable value if it wasn’t read from a file. Filename is also required in
- mode: Mode specifies the kind of code that is to be compiled.
It can be
execif the source consists of a sequence of statements,
evalif it consists of single expression where you can’t use series of the statement and
singleif the source consists of a single interactive statement.
- flags, dont_inherit: Optional. The optional arguments flags and dont_inherit control which future statements (see PEP 236) affect the compilation of source.
The default value of flags is
0and dont_inherit is
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.
Python compile() Example: How Python compile() works?
#Example 1: compile() using exec
>>> 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
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.
#Example 2: compile() using eval
>>> code_object = compile('5+5','string','eval') >>> eval(code_object) 10