15.04.2013 Views

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

14.3.2. compile()<br />

compile() is a function that allows the programmer to generate a code object on the fly, that is, during<br />

runtime. These objects can then be executed or evaluated using the exec statement or eval() BIF. It is<br />

important to bring up the point that both exec and eval() can take string representations of <strong>Python</strong> code<br />

to execute. When executing code given as strings, the process of byte-compiling such code must occur<br />

every time. The compile() function provides a one-time byte-code compilation of code so that the<br />

precompile does not have to take place with each invocation. Naturally, this is an advantage only if the<br />

same pieces of code are executed more than once. In these cases, it is definitely better to precompile<br />

the code.<br />

All three arguments to compile() are required, with the first being a string representing the <strong>Python</strong> code<br />

to compile. The second string, although required, is usually set to the empty string. This parameter<br />

represents the file name (as a string) where this code object is located or can be found. Normal usage is<br />

for compile() to generate a code object from a dynamically generated string of <strong>Python</strong> codecode that<br />

obviously does not originate from an existing file.<br />

The last argument is a string indicating the code object type. There are three possible values:<br />

'eval' Evaluatable expression [to be used with eval()]<br />

'single' Single executable statement [to be used with exec]<br />

'exec' Group of executable statements [to be used with exec]<br />

Evaluatable Expression<br />

>>> eval_code = compile('100 + 200', '', 'eval')<br />

>>> eval(eval_code)<br />

300<br />

Single Executable Statement<br />

>>> single_code = compile('print"Hello world!"', '', 'single')<br />

>>> single_code<br />

<br />

>>> exec single_code<br />

Hello world!<br />

Group of Executable Statements<br />

>>> exec_code = compile("""<br />

... req = input('Count how many numbers? ')<br />

... for eachNum in range(req):<br />

... print eachNum<br />

... """, '', 'exec')<br />

>>> exec exec_code<br />

Count how many numbers? 6<br />

0

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!