compile() Built-in Function
Python - compile()
Python compile() built-in function is used to compile a source code string or a file into a code object that can be executed by the Python interpreter.
The main use of the compile()
function is to dynamically generate code and execute it at runtime.
In this tutorial, we will learn the syntax and usage of compile() built-in function with examples.
Syntax
The syntax of compile() function is
compile(source, filename, mode, flags=0, dont_inherit=False, optimize=- 1)
where
Parameter | Description |
---|---|
source | The source code that needs to be compiled. It can be a string of Python code, a file object, or an AST object. |
filename | The name of the file that contains the source code. If the source code is not associated with a file, you can use any descriptive name. |
mode | The compilation mode. The available modes are: 1. 'exec' : This mode is used for compiling a top-level module, such as a script file or a module. The resulting code object can be executed by calling the exec() built-in function.2. 'eval' : This mode is used for compiling an expression. The resulting code object can be evaluated by calling the eval() built-in function.3. 'single' : This mode is used for compiling a single statement. The resulting code object can be executed by calling the exec() built-in function. |
Example
In the following program, we will take source code in a string, compile the code using compile() built-in function, and then execute the compiled object using exec().
Python Program
code = 'mystring="Hello World"\nprint(mystring)'
x = compile(code, '', 'exec')
exec(x)
Output
Hello World
Uses of compile() method
The compile()
function is commonly used in advanced Python programming scenarios, such as:
- Creating dynamic code at runtime, such as in code generation tools or template engines.
- Performing program analysis and optimization, such as in static analyzers or JIT (Just-In-Time) compilers.
- Implementing custom interpreters or compilers, such as in domain-specific languages or embedded scripting environments.
Summary
In this Built-in Functions tutorial, we learned the syntax of the object() built-in function, and how to use this function to create an empty object.