The compile()
method takes in an input code and returns a code object that can easily be executed.
compile(*source, filename, mode, flags=0, dont_inherit=False, optimize=-1*)
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 is eval
. If the code consists of a single interactive statement, the mode is single
. The exec
mode takes a block of a code that has statements, classes, and functions.
flags
(optional): The default for this is 0
.
dont_inherit
(optional): The default for this is 0
.
optimize
(optional): The optimization level of the compiler can be specified by this. Its default value is -1.
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()
.
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()