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.
The code object returned by the compile() method can later be called using methods like: exec() and eval() which will execute dynamically generated Python code.
The compile() method returns a Python code object.
codeInString = 'a = 5\nb=6\nsum=a+b\nprint("sum =",sum)'
codeObejct = compile(codeInString, 'sumstring', 'exec')
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 exec() method.
The compile() method converts the string to Python code object. The code object is then executed using exec() method.