How to use Python compile

You can use Python compile to execute individual lines of code or a code block and then save the result as a variable. This will give you back a code object that you can then execute.

What can Python compile be used for?

If you don’t want to execute a code statement directly in your Python program, but instead just want to assign it to a variable, you can use the Python compile function. It’s used to change source code into object code and gives you an object back which you can execute using Python exec. You can also assign Python compile a file to extract the source code from.

Tip

Using Python efficiently for your web project? IONOS Deploy Now can help you work more efficiently by letting you deploy your website at any time via GitHub. With a real-time preview, you can view the current status of your project in just a few clicks.

What is the syntax for Python compile?

Python compile can be used with up to six different parameters. Only the first three are necessary though in order to use the function. The remaining parameters are optional and can be used as needed, allowing you to specify how the function should work.

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

To give you a better idea of how the Compile function works, we’ve provided a table of the individual parameters below.

Parameter Optional Description
source no This is where you enter what you want to compile. These are normally strings, but they can also be byte objects or AST objects.
filename no This is where you enter the source file of the object you want to compile. If there is no file, you can enter what you want. This parameter needs to be entered.
mode no With mode, you need to specify how the object should be compiled. You have the following choices:
  • eval: individual phrases can be evaluated with eval.
  • exec: code blocks are analysed with exec.
  • single: for individual, interactive statements, single is used.
flags yes Here you can enter exactly how the source should be compiled. However, in most instances, you can ignore the flag.
dont_inherit yes Exactly like flag, the parameter dont_inherit is used to define the compilation of your source.
optimize yes With the optimize parameter, you can optimise your compilation.

Code examples for Python compile

Let’s take a look at how Python compile works by using an example:

codeAsString = 'x = 10\ny = 7\nres = x * y\nprint("result = ", res)'
codeObject = compile(codeAsString, ' ', 'exec')
exec(codeObject)
python

You can then define a variable called codeAsString, which stores the following simple Python code as a Python string.

x = 10
y = 7
res = x * y
print("result = ", res)
python

Don’t worry about the “\n” in codeAsString. This is simply a control to mark a line break. As you can see, you can set your Python code as a string using a standard variable. However, if you want to ensure that the code isn’t taken as a simple string, you can use the compile function. In the above example, only the required parameters are used in the compile function.

You can now enter what you want to compile, in other words, your string. Following this, you can specify the source file of your string. Since the string is defined directly in the code and not read from a file you can specify the empty string. In theory, you can use any string.

The last parameter is somewhat interesting. Since the string codeAsString is a complete code block (as shown in the resolution of the string in the second code example), we can use the parameter exec. Remember that this is a string, so it needs to have quotation marks.

The results of the compile function are assigned to the codeObject variable. This contains exactly what the name suggests: a code object. What’s special about a code object is that it can be run at any time using the Python exec function. This is exactly what happens in the last line of code, with the result at the end being ‘result=70’.

How to compile a single instruction

When you want to compile a single code instruction, you need to adapt the third parameter when using Python compile. This is because the individual instruction of the mode eval is used. Here’s another example:

singleInstruction = 'print("Hello World!")'
codeObject = compile(singleInstruction, ' ', 'eval')
exec(codeObject)
python

Not much has changed here. The string is still being created with Python code. However, compared with the previous example, the string here has a single Python print instruction. This requires you to use the eval mode, which is used to evaluate individual instructions.

When you execute your code object using the exec function again, you can see that everything works as expected. You should now see ‘Hello World!’ on your screen.

How to process source code from a file

In the previous example, we defined the source code as a string in the program itself. But what if you have a file containing the code you want to execute? In this case, you can use Python compile.

Let’s say that we have a file called testcode.py which contains Python code that we want to execute in our program.

tmpFile = open('testcode.py', 'r')
tmpCode = tmpFile.read()
tmpFile.close()
codeObject = compile(tmpCode, 'testcode.py', 'exec')
exec(codeObject)
python

Now you need to read the code from the file containing it. You can open the file using the Python open function with reading capabilities. Then use Python read to read the source code in your variable called tmpCode. When it’s done, close the file.

Now you can use Python compile. This is the point where you can enter where you got the code from that you want to compile. In this case, it’s the file testcode.py. The program will be similar to the previous examples and using exec, you can execute the code from testcode.py in the program.

Was this article helpful?
Page top