Python compile() function

Explore Python's compile() method for converting code from strings or AST objects into code objects. Learn more about using compile() in Python at rrtutors.com.

Published February 15, 2022

Python compile() is used to return the Python code object, which is either an AST object, a byte string or a normal string.  The method can be used if you want to change your Python code from an AST object or string into a code object.

 

Syntax

Compile() has the following syntax:

Compile(source, name, flags=0, mode, don’t_inherit=False, optimize=-1)

Where:

  • Source- source of the  byte string, normal string or AST object

  • Name-  the name of the file which will be read by the code

  • Mode- the mode can either be  single or eval or exec

  • Flags- the default value is set to o

  • Optimize- defines the optimization level of the compiler

Example

Here is an example of how compile() works

srcCode = 'x = 20\ny = 30\nmul = x * y\nprint("mul =", mul)'

execCode = compile(srcCode, 'mulstring', 'exec')

exec(execCode)

Output

mul = 600

 

Related Tutorials & Resources