Python compile() function With Examples

Python compile() function is used to compile the source into code object or AST module object. The returned code object can be executed using exec() or eval() function based on the provided mode to construct the code object.

Python compile()

Python compile() function syntax is:

Let’s look at the compile() function arguments.

  • source: Source to create the code object. This can be string, byte string or AST module object.
  • filename: If you are reading code string from a file, you should provide its name here for reference. It’s not used in creating the code object, rather it’s used for making code readable.
  • mode: This argument specifies the type of code. Allowed values are exec, eval and single. Use exec if source contains multiple python statements. Use eval if source is a single python expression. Use single if source consists of a single interactive statement.
  • The optional arguments flags and dont_inherit control which future statements affect the compilation of source. If neither is present (or both are zero) the code is compiled with those future statements that are in effect in the code that is calling compile().
  • The argument optimize specifies the optimization level of the compiler.

Python compile() examples

Let’s look at compile() function example with different sources.

Compiling String Source to Code


Notice that the compile function return type is ‘code’ object. Also, we are using exec() here because source string contains multiple python statements. Notice that code object is being executed by the exec() function and “sum = 15” is getting printed in the console.

Reading Code from a File and Compiling

Let’s say we have file with following content.

We can read this file content as a string and compile it to code object and execute it.

Output: Multiplication = 200

compile() with eval()

Let’s see an example to compile python expression to code and execute it using eval() function.


compile() with byte string source

Let’s look at an example of using byte string as source.


compile() with AST Object

Let’s look at an example of using AST object with compile() function.



Python compile() function allows us to create code object from a string, which can be later executed using exec() and eval() functions. You should take extra care if you are taking user input and compile it to code and execute it because it can have unwanted effects, for example issuing rm -rf / command.

You can checkout complete python script and more Python examples from our GitHub Repository.

Reference: Official Documentation

By admin

Leave a Reply

%d bloggers like this: