[Python-porting] co_names behavior change

Tom Ekberg tekberg at uw.edu
Mon Apr 8 17:20:05 EDT 2019


Being an old-time compiler person, I ended up using the symtable module and recursively called child.get_identifiers() to get all of the names. Attached is the diff (ignore the last 2 parts of the diff). It works with python 2.7 and 3.5.


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


________________________________
From: Piet van Oostrum <piet-l at vanoostrum.org>
Sent: Monday, April 8, 2019 1:59 PM
To: Tom Ekberg
Cc: Python-porting at python.org
Subject: Re: [Python-porting] co_names behavior change

You can get the variable names of the embedded comprehensions with:

[lc.co_names for lc in f.__code__.co_consts if  type(lc) is types.CodeType]

where f is the function defined by the exec (f = d['f'])

But to take nested comprehensions into account you would have to write a recursive function:

from types import CodeType

def varnames(codeobj):
    names = [lc.co_names for lc in codeobj.co_consts if isinstance(lc, CodeType)]
    names += [varnames(lc) for lc in codeobj.co_consts if isinstance(lc, CodeType)]
    # flatten the list
    return [item for sublist in names for item in sublist]

print(varnames(f.__code__))

--
Piet van Oostrum <piet-l at vanoostrum.org>
WWW: http://piet.vanoostrum.org/
piet . van oostrum – Mijn Blog<http://piet.vanoostrum.org/>
piet.vanoostrum.org
Op 22 december hebben we mijn verjaardag gevierd met een barbequeue in restaurant `Los Jardines’ (De Tuinen), hetzelfde restaurant waar we een week geleden het kerstdiner van het MEMI hadden. Het was de eerste keer dat mijn verjaardag in de zomer was.


PGP key: [8DAE142BE17999C4]

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-porting/attachments/20190408/d1a6eda4/attachment.html>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: PythonExpr.py.diff
Type: application/octet-stream
Size: 2259 bytes
Desc: PythonExpr.py.diff
URL: <http://mail.python.org/pipermail/python-porting/attachments/20190408/d1a6eda4/attachment.obj>


More information about the Python-porting mailing list