[Python-porting] co_names behavior change

Tom Ekberg tekberg at uw.edu
Mon Mar 25 11:08:39 EDT 2019


I'm using the roundup program which has been ported from Python 2.7 to Python 3.x. My group uses this program internally to track progress and document issues. Roundup is written in Python and has a templating language (TAL) that allows one to define a Python expression. This is implemented by constructing a function:


            d = {}
            exec('def f():\n return %s\n' % expr.strip(), d)
            self._f = d['f']


where expr contains the Python expression. To reference variables defined in the templating language it constructs a list of variable names using the names in self.__code__.co_names:


        self._f_varnames = vnames = []
        for vname in self._f.__code__.co_names:
            if vname[0] not in '$_':


This works fine for Python 2.7. However for Python 3.5, the value of self._f.__code__.co_names does not always contain all names referenced in the expression. When the function is executed it generates an exception saying that a variable being referenced is undefined. Some expression work correctly, some do not. I have documented an example that fails in the roundup bug tracking database: https://issues.roundup-tracker.org/issue2551026. I came up with a roundup patch that implements variation that works for both Python 2.7 and Python 3.5.


My question to this group:


Do you have knowledge of the different contents of __code__.co_names between Python 2.7 and Python 3.5? I'm expecting that this is a difference that is documented somewhere.


I have attached an example that illustrates this problem.


Tom Ekberg
Senior Computer Specialist, Lab Medicine
4th Floor, Pat Steel Building
Department of Laboratory Medicine
Work: (206) 520-4856
Email: tekberg at uw.edu
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-porting/attachments/20190325/ec936ce8/attachment.html>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: python_bug.py
Type: application/octet-stream
Size: 1050 bytes
Desc: python_bug.py
URL: <http://mail.python.org/pipermail/python-porting/attachments/20190325/ec936ce8/attachment.obj>


More information about the Python-porting mailing list