compiler package vs parser

Robin Becker robin at reportlab.com
Thu Apr 16 05:41:56 EDT 2009


Is the compiler package actually supposed to be equivalent to the parser module?

I ask because the following code

#### start p.py
def func(D):
     for k in D:
         exec '%s=D[%r]' % (k,k)
     print i, j, k
     print locals()
     print i, j, k

if __name__=='__main__':
     func(dict(i=1,j=33))
#### end p.py

when run through the compiler package to produce a module has different code to 
that produced by the standard compilation (detected by dis.dis). In particular 
the variables i and j in func above are treated differently; in the standard 
compiler case LOAD_NAME is used and in the code from the package LOAD_GLOBAL is 
used.

The code used to create the synthetic module is

#### start tp.py
from compiler import parse, pycodegen, misc, syntax
import time, struct, marshal
txt=open('p.py','r').read()

tree=parse(txt)
print 'tree\n',tree

def _get_tree(tree,filename):
	misc.set_filename(filename, tree)
	syntax.check(tree)
	return tree

def getPycHeader():
	mtime = time.time()
	mtime = struct.pack('<i', mtime)
	return pycodegen.Module.MAGIC + mtime

def dump(fn,code):
	f=open(fn,'wb')
	f.write(getPycHeader())
	marshal.dump(code,f)
	f.close()

gen = pycodegen.ModuleCodeGenerator(_get_tree(tree,'synp.py'))
code = gen.getCode()

dump('synp.pyc',code)
#### end tp.py

The module synp.pyc fails with a traceback (as expected because there are no 
global i,j), but p.py runs OK.

I assume that my attempt to compile the tree is broken (is missing some special 
traverse etc) otherwise the code would end up the same (except for line 
numbering which I have ignored).
-- 
Robin Becker




More information about the Python-list mailing list