Compile(): Consider a situation where we have a piece of Python code in a string and we want to compile it so that we can later run it when needed. The compile method does this task. It takes sourcecode as input and returns a code object which is ready to be executed.
compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)
Source – It can be a normal string, a byte string, or an AST object
Filename -This is the file from which the code was read. If it wasn’t read from a file, you can give a name yourself.
Mode – Mode can be exec, eval or single.
a. eval – If the sorce is a single expression.
b. exec – It can take a block of a code that has Python statements, class and functions and so on.
c. single – It is used if consists of a single interactive statement
Flags (optional) and dont_inherit (optional) – Default value=0. It takes care that which future statements affect the compilation of the source.
Optimize (optional) – It tells optimization level of compiler. Default value -1.
mul = 200
- If the Python code is in string form or is an AST object, and you want to change it to a code object, then you can use compile() method.
- The code object returned by the compile() method can later be called using methods like: exec() and eval() which will execute dynamically generated Python code.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.
- How to Compile and Run C/C++/Java Programs in Linux
- Python - Call function from another function
- Wand function() function in Python
- Returning a function from a function - Python
- wxPython - GetField() function function in wx.StatusBar
- How to write an empty function in Python - pass statement?
- Function Decorators in Python | Set 1 (Introduction)
- Vulnerability in input() function – Python 2.x
- Function Annotations in Python
- Sorted() function in Python
- Ways to sort list of dictionaries by values in Python - Using lambda function
- Python Numbers | choice() function
- Python | askopenfile() function in Tkinter
- Python | Binding function in Tkinter
- floor() and ceil() function Python
- ord() function in Python
- round() function in Python
- id() function in Python
- vars() function in Python
- Print powers using Anonymous Function in Python
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.