The syntax of compile() is:
compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)
The compile() method is used if the Python code is in string form or is an AST object, and you want to change it to a code object.
source- a normal string, a byte string, or an AST object
filename- file from which the code was read. If it wasn't read from a file, you can give a name yourself
eval- accepts only a single expression.
exec- It can take a code block that has Python statements, class and functions and so on.
single- if it consists of a single interactive statement
dont_inherit(optional) - controls which future statements affect the compilation of the source. Default Value: 0
optimize(optional) - optimization level of the compiler. Default value -1.
The compile() method returns a Python code object.
codeInString = 'a = 5\nb=6\nsum=a+b\nprint("sum =",sum)' codeObejct = compile(codeInString, 'sumstring', 'exec') exec(codeObejct)
When you run the program, the output will be:
sum = 11
Here, the source is in normal string form. The filename is sumstring. And, the
exec mode later allows the use of
The compile() method converts the string to Python code object. The code object is then executed using exec() method.