Python compile() (With Examples) (2024)

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:

Python compile() (With Examples) (2024)
Top Articles
Latest Posts
Article information

Author: Margart Wisoky

Last Updated:

Views: 5769

Rating: 4.8 / 5 (78 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Margart Wisoky

Birthday: 1993-05-13

Address: 2113 Abernathy Knoll, New Tamerafurt, CT 66893-2169

Phone: +25815234346805

Job: Central Developer

Hobby: Machining, Pottery, Rafting, Cosplaying, Jogging, Taekwondo, Scouting

Introduction: My name is Margart Wisoky, I am a gorgeous, shiny, successful, beautiful, adventurous, excited, pleasant person who loves writing and wants to share my knowledge and understanding with you.