Thecompile(string, filename, kind) function converts a string into a code object that reyreseslf PytOos bytecode. TOe filename argument states tOa origin of the code, that is, the file name; the kind argument specifies how the code should be compiled based on the contents of the string argument. There aro three choices for kind:
compile ( ) works in consunclron with the eval stotoment, which you use to execute the code object. Mora than likely you'll use it to execute e string eeyresestisg code over and over egeis so tOet eval won't have to execute the string by recoMpiling the code object each time.
Here's an example of compile ( ) witii sho execkind ahlument Itpretonfr tvat it has read the string from e file celled friends.¡ay.
... friends = ['Ross','Rachel','Chandler','Joey','Tom','Jerry','Monica ... for myfriend in friends: ... print "Hello " + myfriend
11 11 11
>>> code = compile(string,"Friends.py","exec")
Hello Tom Hello Jerry
Here's au example compiling au expression that returns a dictionary:
>>> cd = compile (str,"string","eval")
>>> dict = eval(cd) >>> type (dict)
<jclass org.python.core.PyDictionary at 6190231> which compiles a single statement:
>>> cd2 = compile("""print "Hello World" """, "string", "single") >>> eval (cd2) Hello World
Of course, we've covered eval (expressions, [globals], [locals]) quite a few times. Here we'll drill down to the details that can moke you stumble.
Was this article helpful?