Python compile() function with examples

In this post, we are going to talk about Python compile() function with examples. This built-in function is used to make a string of Python code executable. It takes the string that contains Python code and returns an executable code object for that. We can execute it using different methods later in our program. Let’s discuss compile() function in detail.

Python compile() function: Syntax and Parameters

The syntax of the compile() function is as follows:

compile(source, filename, mode, flags = 0, dont_inherit = False, optimize = -1)

Let’s have a look at the parameter of this function.

source – Normally, the source is the string that is to be executed.

filename – The name of the file from that contains the code. In case, the source code wasn’t read from a file, any name can be given.

mode – The mode can be eval, exec or single. eval is used when the source code consists of a single expression. We can use exec for a sequence of statements and mode single when the source is a single interactive statement.

flags and  dont_inherit– The flags and dont_inherit parameters are optional. These parameters are used to control which future statements affect the compilation of the source code.

optimize – This parameter is also optional. This parameter is used to specify the optimization level of the compiler.

To gain more knowledge on this, you can visit this page: Read this.

Examples

Now, let us see some examples that will explain the working of the compile() function in Python.

The below example shows the working of the compile() function in exec mode for a multiline Python code.

src = "print('First line')\nprint('Second line')"

code_obj = compile(src, 'any_name', 'exec')

exec(code_obj)

Output:

First line
Second line

In the following example, we have used the compile() function in eval mode. You can see, we have provided a single expression as the source.

src = 'print(5)'

code_obj = compile(src, 'any_name', 'eval')

exec(code_obj)

Output:

5

The below example shows the use of the compile() function with the mode parameter given as single.

a = 4

code_obj = compile('a * a', 'any_name', 'single')

exec(code_obj)

Output:

16

We can also use the eval() method to execute the object code.

Thank you.

Also read: Python hash() Function

Leave a Reply

Your email address will not be published. Required fields are marked *