Python compile() function
Published February 15, 2022Python compile() is used to return the Python code object, which is either an AST object, a byte string or a normal string. The method can be used if you want to change your Python code from an AST object or string into a code object.
Syntax
Compile() has the following syntax:
Compile(source, name, flags=0, mode, don’t_inherit=False, optimize=-1) |
Where:
-
Source- source of the byte string, normal string or AST object
-
Name- the name of the file which will be read by the code
-
Mode- the mode can either be single or eval or exec
-
Flags- the default value is set to o
-
Optimize- defines the optimization level of the compiler
Example
Here is an example of how compile() works
srcCode = 'x = 20\ny = 30\nmul = x * y\nprint("mul =", mul)' execCode = compile(srcCode, 'mulstring', 'exec') exec(execCode) |
Output
mul = 600 |
Article Contributed By :
|
|
|
|
237 Views |