Showing posts with label complie() function in python. Show all posts
Showing posts with label complie() function in python. Show all posts

Saturday, November 7, 2020

, ,

Example Program for complie() function in python - Python Program

 

 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.

 flags (optional) and dont_inherit : - if any problem stop to compile the source then it raise flag. default value : -0

 optimize (optional) - optimization level with Default value -1 for compiler.

Example Program for complie() function
Example Program for complie() function

 

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)

OUTPUT

sum = 11

compile function in python convert the string into a python code object and then execute with exec() method