DEV Community

kenny844
kenny844

Posted on

Program for Compile function in python

The complie() function in python is used to return python code object from a source like (string,AST object,byte string).
Syntax For Complie(): -

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

Well the return object from the compile function in python can be called by exec() and eval() method.
Parameter : -

A source that can be used in compile function that can be normal string, a byte string, or an AST object.

A code that can be read from a file. If it doesn't read form a file then you give a name according to you.

Either exec,eval or signal method can be used to call a function.

Well eval accept only a single expression.

exec take block of code with python statement like class function.

it contain single interactive statement.

Example program for compile() function in python : -

codeInString = 'a = 5\nb=6\nsum=a+b\nprint("sum =",sum)'
codeObejct = compile(codeInString, 'sumstring', 'exec')

exec(codeObejct)
Enter fullscreen mode Exit fullscreen mode

OUTPUT

sum = 11

Read the article here: Tutorial for function

Top comments (0)