You can use Python compile to execute in­di­vidu­al 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 ef­fi­ciently for your web project? IONOS Deploy Now can help you work more ef­fi­ciently 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 para­met­ers. Only the first three are necessary though in order to use the function. The remaining para­met­ers 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 in­di­vidu­al para­met­ers below.

Parameter Optional De­scrip­tion
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: in­di­vidu­al phrases can be evaluated with eval.
  • exec: code blocks are analysed with exec.
  • single: for in­di­vidu­al, in­ter­act­ive state­ments, 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 com­pil­a­tion of your source.
optimize yes With the optimize parameter, you can optimise your com­pil­a­tion.

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 code­As­String, 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 code­As­String. 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 para­met­ers 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 in­ter­est­ing. Since the string code­As­String is a complete code block (as shown in the res­ol­u­tion 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 codeO­b­ject 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 in­struc­tion

When you want to compile a single code in­struc­tion, you need to adapt the third parameter when using Python compile. This is because the in­di­vidu­al in­struc­tion 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 in­struc­tion. This requires you to use the eval mode, which is used to evaluate in­di­vidu­al in­struc­tions.

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 con­tain­ing 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 con­tain­ing it. You can open the file using the Python open function with reading cap­ab­il­it­ies. 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.

Go to Main Menu