Python compile() function

Filed Under: Python

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:


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

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


# compile() with string source
code_str = 'x=5\ny=10\nprint("sum =",x+y)'
code = compile(code_str, 'sum.py', 'exec')
print(type(code))
exec(code)

Output:


<class 'code'>
sum = 15

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 my_code.py file with following content.


x = 10
y = 20
print('Multiplication = ', x * y)

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


# reading code from a file
f = open('my_code.py', 'r')
code_str = f.read()
f.close()
code = compile(code_str, 'my_code.py', 'exec')
exec(code)

Output: Multiplication = 200

compile() with eval()

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


# eval example
x = 5
code = compile('x == 5', '', 'eval')
result = eval(code)
print(result)

code = compile('x + 5', '', 'eval')
result = eval(code)
print(result)

Output:


True
10

compile() with byte string source

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


bytes_str = bytes('x == 5', 'utf-8')
print(type(bytes_str))
code = compile(bytes_str, '', 'eval')
result = eval(code)
print(result)

Output:


<class 'bytes'>
True

compile() with AST Object

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


import ast

ast_object = ast.parse("print('Hello world!')")
print(type(ast_object))
code = compile(ast_object, filename="", mode="exec")
print(type(code))
exec(code)

Output:


<class '_ast.Module'>
<class 'code'glt;
Hello world!

Summary

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

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages