What is compile() in Python?
The compile() method takes in an input code and returns a code object that can easily be executed.
Syntax
compile(*source, filename, mode, flags=0, dont_inherit=False, optimize=-1*)
Parameters
-
source: The source can be an AST object or a normal/byte string. -
filename: The file from where we read the code. -
mode: There are three types of mode. For a single expression source, the mode iseval. If the code consists of a single interactive statement, the mode issingle. Theexecmode takes a block of a code that has statements, classes, and functions. -
flags(optional): The default for this is0. -
dont_inherit(optional): The default for this is0. -
optimize(optional): The optimization level of the compiler can be specified by this. Its default value is -1.
Use
If the Python code you have is in the form of a string or an AST object and you need to change it to a code object, use compile().
Code
number = 30x = compile('number', 'test', 'single')eval(x)
In order to execute the result returned by
compile(), there are two inbuilt functions that can be used:
exec()eval()