1.

Explain how built-in compile() function works

Answer»

According to Python’s standard documentation, compile() function returns code object from a string containing valid Python statements, a byte string or AST object.

A code object represents byte-compiled executable version of Python code or simply a BYTECODE. AST STANDS for Abstract syntax tree. The AST object is obtained by parsing a string containing Python code.

Syntax of compile() function looks as follows:

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

The source parameter can be a string, bytestring or AST object. Filename parameter is required if you are reading code from a file. The code object can be executed by exec() or eval() functions which is mode parameter. Other parameters are optional.

Thee FOLLOWING example compiles given string to a code object for it to be executed using exec() function.

>>> string=''' x=10 y=20 z=x+y print (z) ''' >>> obj=compile(string,'addition', 'exec') >>> exec(obj) 30

The following example uses eval as mode parameter in compile() function. Resulting code object is executed using eval() function.

>>> x=10 >>> obj=compile('x**2', 'square','eval') >>> VAL=eval(obj) >>> val 100

The AST object is first obtained by parse() function which is defined in ast module. It in turn is used to compile a code object.

>>> import ast >>> astobj=parse(string) >>> astobj=ast.parse(string) >>> obj=compile(astobj,'addition', 'exec') >>> exec(obj) 30


Discussion

No Comment Found