![]() |
VOOZH | about |
Python is a high-level, general-purpose, and very popular programming language. In this article, we will learn about the Python compile() function.
Python compile() function takes source code as input and returns a code object that is ready to be executed and which can later be executed by the exec() function.
Syntax compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)
Parameters:
- 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 source 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.
Example 1: Here filename is mulstring and exec mode allows the use of exec() method and the compile method converts the string to a Python code object.
Output:
mul = 200Example 2: In the code we are using compile() to compile a single expression 'x' and then execute it using exec().
Output:
<class 'code'>
50
In this example, we will take main.py file with some string display methods, and then we read the file content and compile it to code the object and execute it.
Here we will read the file content as a string and then compile it to a code object.
Output:
Welcome to GeeksforgeeksHere eval is used when the source is a single expression.
Output:
True