The python compile() function takes source code as input and returns a code object which can later be executed by exec() function.
It has the following syntax:
It returns a Python code object.
Let's see some examples of compile() function which are given below:
In this example, the compile() function is used to convert a string of code into a code object, which is then executed using exec() to run the program dynamically.
Python
Execute NowOutput:
<class 'code'> sum = 15
In this example, Python code is read from a file as a string, compiled into a code object using compile(), and then executed using exec() to run the file content dynamically.
Let's say we have mycode.py file with following content.
Python
We can read this file content as a string ,compile it to code object and execute it.
Execute NowOutput:
Multiplication =200
We request you to subscribe our newsletter for upcoming updates.