Home >>Python Built-in Functions >Python compile() Function

Python compile() Function

Python compile() Function

The compile() function takes source code as input and returns the specified source as a code object which can later be executed by exec() function.

Syntax:
compile(source, filename, mode, flag, dont_inherit, optimize)

Parameter Values

Parameter Description
source It is Required Parameter. The source to compile, a normal String, a byte string, or an AST (Abstract Syntax trees) object
filename It is Required Parameter. The name of the file from which the code is read.
mode It is Required Parameter. Legal values:
eval – In case the source is a single expression
exec – In case the source is a block of statements
single – In case the source is a single interactive statement
flags It is Optional parameter. It monitors that how to compile the source. Default value is 0
dont-inherit It is Optional parameter. It monitors that how to compile the source. Default value is 0
optimize It is Optional parameter. It defines the optimization level of the compiler and its default value is -1
Here is an Example of Python compile() Function:
z = compile('print(85)', 'test', 'eval')
exec(z)
Output:
85
Example 2:
Sourcecode = 'a = 15\nb = 25\nmul = a * b\nprint("mul =", mul)'
execCode = compile(Sourcecode, 'mulstring', 'exec') 
exec(execCode)
Output:
mul = 375

Python Built-in Functions Python abs() Function Python all() Function Python any() Function Python ascii() Function Python bin() Function Python bool() Function Python bytearray() Function Python bytes() Function Python callable() Function Python chr() Function Python compile() Function Python complex() Function Python delattr() Function Python dict() Function Python dir() Function Python divmod() Function Python enumerate() Function Python eval() Function Python exec() Function Python filter() Function Python float() Function Python format() Function Python frozenset() Function Python getattr() Function Python globals() Function Python hasattr() Function Python hash() Function Python help() Function Python hex() Function Python id() Function Python input() Function Python int() Function Python isinstance() Function Python issubclass() Function Python iter() Function Python len() Function Python list() Function Python locals() Function Python map() Function Python max() Function Python memoryview() Function Python min() Function Python next() Function Python object() Function Python oct() Function Python open() Function Python ord() Function Python pow() Function Python print() Function Python property() function Python range() Function Python repr() Function Python reversed() Function Python round() Function Python set() Function Python setattr() Function Python slice() Function Python sorted() Function Python str() Function Python sum() Function Python super() Function Python tuple() Function Python type() Function Python vars() Function Python zip() Function
No Sidebar ads