Python compile()

The compile() method computes the Python code from a source object and returns it.

Example

codeInString = 'a = 8\nb=7\nsum=a+b\nprint("sum =",sum)'
codeObject = compile(codeInString, 'sumstring', 'exec')

exec(codeObject)

# Output: 15

compile() Syntax

The syntax of compile() is:

compile(source, filename, mode)

compile() Parameters

The compile() method takes in the following parameters:

  • source - a normal string , a byte string, or an AST object
  • filename - file from which the code is to be read
  • mode - exec (can take a code block with statements, class and functions ), eval (accepts single expression) or single (has a single interactive statement)

Note: There are other optional parameters such as flags, dont_inherit and optimize for the compile() method but normally, we don't use them.


compile() Return Value

The compile() method returns

  • a python object code

Example: Python compile()

codeInString = 'a = 5\nb=6\nmul=a*b\nprint("mul =",mul)'
codeObject = compile(codeInString, 'multiplyNumbers', 'exec')

exec(codeObject)

# Output: mul = 30

In the above example, the source argument is the string variable codeInString which has the python object code:

'a = 5\nb=6\nmul=a*b\nprint("mul =",mul)'

We have a compile method to compile the source:

compile(codeInString, 'sumstring', 'exec') 

Where,

  • filename is sumstring
  • mode is exec
  • the variable passed is codeInString

We have assigned the compile() method in exec mode to the codeObject variable.

The exec() method executes the codeObject variable and returns the resulting python object.


Also Read:

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges