AMZ DIGICOM

Digital Communication

AMZ DIGICOM

Digital Communication

Python Compile: apply the function correctly

PARTAGEZ

To directly execute individual lines of code or a block of code and store the result in a variable, you can use the Python Compile function. It returns you a code object that you can execute.

Possible applications

If you don’t want to execute individual code statements directly in your Python program, but only assign them to a variable, you can use the Python Compile function. It is used to convert source code to object code and returns you an object which you can then run using Python exec. You can also pass a file to the Python Compile function from which the source code is extracted.

Are you using Python as an efficient programming language for your web project? Deploy Now from IONOS can help boost your efficiency by deploying your websites anytime via GitHub. The real-time preview allows you to view the current status of your project live at any time with just a few clicks.

Python Compile Syntax

The Python Compile function can be called with up to six different settings, but only the first three parameters are required. The other parameters of the function are optional and can be set as needed to specify the behavior of the function.

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

python

You can better understand the Compile function by going around the individual parameters.

Setting Optional Description
source No You pass here what you want to compile. These are mostly strings, but you can also pass byte objects or AST objects.
filename No At this point, you specify the source of the object file to compile. If there is no file, you can write whatever you want. However, the parameter still needs to be set.
fashion No In the mode parameter, you specify how to compile. You can choose between the following values:

  • eval: the different expressions are evaluated with eval.
  • exec: code blocks are evaluated with exec.
  • simple: you use single for interactive individual statements.
flags Yes Here you can specify how the source should be compiled precisely. However, you can ignore this flag for the vast majority of use cases.
dont_inherit Yes Like flag, the dont_inherit parameter is used to specify the compilation of your source.
optimize Yes The optimize parameter allows you to determine the level of optimization of your compilation process.

Applying Python Compile

We can rely on a code example to illustrate how Python Compile works:

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

python

First, define the variable named 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 be confused by the presence of « \n » in the codeAsString, because this is the control character that marks a line break. So you see that you can simply store your Python code as string in a current variable. However, you need the Compile function to ensure that the code will not only be interpreted as a simple string. The Compile function call in the example above uses only the required parameters.

First you pass what you want to compile, which is your string. You then specify the file source for your channel. As the string was defined directly in the code and was not read from a file, it suffices to specify the empty string. In theory, however, you can use any string you like.

The last parameter arouses our attention again: since our string codeAsString is a entire code blockas the string resolution in the second code example shows, we use the parameter executive. Keep in mind that this is a string, so don’t forget the quotes.

The result of the Python Compile function is assigned to the variable named codeObject in the sample code above. It now contains precisely what its name suggests: a code object. The special aspect of a code object is that you can run it at any time with a call to the exec function in Python. This is exactly what happens in the last line of code, so the program will ultimately output « result=70 ».

Compile a single statement

If you want to compile only one statement of code, you have to adjust third parameter when calling Python Compile function. This is because eval mode is used for individual statements. An example enlightens us here too:

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

python

In fact, not much has changed here. Here too, a string containing Python code is created. Unlike the previous example, the string contains only one Python print statement. This requires the use of evaluation modewhich is invoked for evaluate individual instructions.

Now if you run your code object again using the exec function, you will see that everything works as expected. Your program displays « Hello World! »  » on the screen.

Process source code from file sources

In the previous examples, we always defined the source code that the Python Compile function should treat as a string in the program itself. But what if you have a file containing code that you want to run in your program? You can also implement Python Compile for this purpose.

Suppose you have a file named testcode.py which contains Python executable code and you now want to run it in your program:

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

python

First you need to read the code you want to run from the file it is currently in. To do this, open the file with the open function in Python and read-only access. You can then use Python Read to read the source code into your variable called tmpCode and close the initially opened file.

The code switches to calling Python Compile now. At this point it is important to specify where the code you want to compile comes from – in this case, from the file testcode.py. Our program then resembles the previous examples, and you finally run the code from testcode.py in your program with the final exec call.

Télécharger notre livre blanc

Comment construire une stratégie de marketing digital ?

Le guide indispensable pour promouvoir votre marque en ligne

En savoir plus

Souhaitez vous Booster votre Business?

écrivez-nous et restez en contact