compile(): Create Code or AST Object Function
compile | |
---|---|
Language | Python |
Category | Function |
Part Of | Built In Functions |
Named Arguments Count | 3 |
Unnamed Arguments Count | 3 |
Official Documentation | compile Function |
1 Description
The Python compile
function accepts as input a string of python code
and produces as output a code or AST object which can be executed using the exec() or
eval functions.
2 Prototype
Below is the function prototype for the compile
function.
compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)
3 Arguments
compile Function Arguments | ||||
---|---|---|---|---|
Name | Type | Default Value | Category | Description |
source |
string |
Unnamed argument(s) | The python source code you would like to compile into a code object, as a string object. | |
filename |
string |
|
Unnamed argument(s) | The name of the file that holds the python source code you would like to compile. |
mode |
string |
|
Unnamed Argument(s) |
There are three legal values for the mode argument. They are exec if you are
trying to compile a sequence of statements; eval if you are trying to
compile a single expression; and single if you want to compile a
single statement.
|
flags |
int |
0 |
Keyword argument | The options you would like to pass to the Python compiler. |
dont_inherit |
boolean |
False |
Keyword argument | When dont_inherit is true the options passed to the python code that calls compile will be passed on through to the compiler. When dont_inherit is false (the default) the options passed to the python code that calls compile will not be passed through to the compiler. |
optimize |
int |
-1 |
Keyword argument | There are four legal values for the optimize argument. The first legal value is -1 (the default) which tells the compiler to select the optimization level of the interpreter given -O by the option. The second legal value is 0 which tells the compiler to avoid optimization. The third legal value is 1 which tells the compiler to optimize the output by removing asserts and setting __debug__ to false. The fourth legal value is 2 which will remove docstrings. |
4 Returns
compile Function Returns | |
---|---|
Return Type | Explanation |
AST object |
The compile function will return an ast object. |
code object |
The compile function will return a code object. |
5 Examples
5.1 Compile Hello World
In the python file below we make a single call to the compile
function to
compile a simple string of python code.
#!/usr/bin/python3
def main():
compile()
if __name__ == "__main__":
main()
Now we can run the python file and see how our code is compiled.
user-1@vm:~/Documents$ ./compile_example_1.py
Compiled
user-1@vm:~/Documents$
This document was last updated: