Python compile()
Python compile() builtin function is used to evaluate or execute a piece of code provided as string or bytes or an AST object.
In this tutorial, we will learn about the syntax of Python compile() function, and learn how to use this function with the help of examples.
Syntax
The syntax of compile() function is
</>
Copy
compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)
where
Parameter | Required/ Optional | Description |
---|---|---|
source | Required | The source to compile. It can be a String, a Bytes object, or an AST object |
filename | Required | The name of the file that the source comes from. If the source does not come from a file, this value is ignored, and we can provide any value for this parameter. |
mode | Required | One of the following three values is allowed. ‘eval’ – if the source is a single expression ‘exec’ – if the source is a block of statements ‘single’ – if the source is a single interactive statement |
flags | Optional | Tells how to compile the source. Default value is 0. |
dont-inherit | Optional | Default value is False. |
optimize | Optional | Defines the optimization level of the compiler. Default value is -1. |
Examples
1. Compile Python Statement from String
In this example, we take print statement as a string in variable a
, and evaluate it using compile() function.
Python Program
</>
Copy
a = 'print("Hello World!")\nprint("hello world")'
x = compile(a, '', 'exec')
exec(x)
Output
Hello World!
hello world
Conclusion
In this Python Tutorial, we have learnt the syntax of Python compile() builtin function, and also learned how to use this function, with the help of Python example programs.