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

compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)

where

ParameterRequired/OptionalDescription
sourceRequiredThe source to compile. It can be a String, a Bytes object, or an AST object
filenameRequiredThe 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.
modeRequiredOne 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
flagsOptionalTells how to compile the source. Default value is 0.
dont-inheritOptionalDefault value is False.
optimizeOptionalDefines the optimization level of the compiler. Default value is -1.

Examples

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

a = 'print("Hello World!")\nprint("hello world")'
x = compile(a, '', 'exec')
exec(x)
Try Online

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.