How to Use the Python compile() Function

09/18/2021

Contents

In this article, you will learn how to use the Python compile() function.

Python compile() Function

The compile() function in Python is used to compile a string of source code into a code object or AST (Abstract Syntax Tree) representation. This can be useful for dynamically generating and executing code at runtime, or for analyzing code for syntax errors and other issues.

Here’s how you can use the compile() function:

code = "print('Hello, world!')"
compiled_code = compile(code, "", "exec")
exec(compiled_code)

In this example, we have a string of code that simply prints “Hello, world!”. We pass this code to the compile() function, along with two additional arguments:

  • The second argument, “<string>”, is the filename that will be used in any error messages that result from executing the compiled code. You can use any string you like here, as long as it’s a valid filename.
  • The third argument, “exec”, specifies the mode in which the code will be compiled. There are three possible modes: “exec” (for code that will be executed as a series of statements), “eval” (for code that will be evaluated and returned as a single value), and “single” (for code that consists of a single interactive statement).

The compile() function returns a code object that represents the compiled code. We can then pass this code object to the exec() function to actually execute the code.

Note that the compile() function can also be used to compile code from a file or from an AST object, in addition to a string of code. The arguments you pass to the function will depend on how you’re compiling the code.