89DEVs

Python compile() function

The compile() function accepts source code and returns it into an object that can be executed. To execute the object, use the exec() function or eval() function. The exec() function can accept a block of code, while the eval() function accepts a single expression.

The compile() function is useful when the code is in string format or if we want to read the code from a file.

compile() code in string format

If the code is in string format, we can not execute it directly. Use the compile() method to convert it to executable code. # compile() code in string format myCode = 'number1 = 1 \nnumber2 = 4 \nresult = number1 + number2 \nprint(result)' executableCode = compile(myCode, 'null', 'exec') exec(executableCode) We first use compile() to compile the code into executable code, then we execute the code and the result is returned. 5

compile() a single statement

In this example, we compile a single statement and execute it via eval(). # compile() a single statement and eval() myInt = 25 myCode = compile('myInt', 'null', 'single') eval(myCode) The statement is compiled and executed with the eval() function. The result 25 is returned. 25

compile code from a file

In this example, the python file mycode.py contains the following code. # mycode.py myString = 'my favorite number is ' myNumber = 777 print(myString + str(myNumber)) We can now read the file, compile the code and then finally execute it. # compile code from file f = open('mycode.py', 'r') t = f.read() f.close() myCode = compile(t, 'mycode.py', 'exec') exec(myCode) The code is compiled, executed and the result is returned. my favorite number is 777

compile() syntax

The syntax of the compile() function is: compile(source, file, mode, flags=0, dont_inherit=0, optimize=-1)

compile() arguments

The compile() functions accepts 3-5 arguments:
  • required: source, the source code to compile
  • required: file, the filename of the code
  • required: mode, either 'exec', 'eval' or 'single'
  • optional: flags, allows to set flags
  • optional: dont_inherit, defines inheritance
  • optional: optimize, optimization level of the compiler
If the code was not read from a file, give the file argument any value. It is not evaluated, but the file argument is still required. For the mode: If the code is a single statement, use eval. If it is a code block use eval and for a single interactive statement use single. If the required arguments are missing, a TypeError exception is raised.

compile() return value

The compile() function returns executable code. <class 'code'>

related functions

Use the exec() or eval() function to execute the compiled code. The exec() function is used for code blocks, while the eval() function accepts a single expression.

                
        

Summary


Click to jump to section