'_[1]' in .co_names using builtin compile() in Python 2.6

Ian Kelly ian.g.kelly at gmail.com
Wed Nov 27 21:23:14 CET 2013

On Nov 27, 2013 2:11 PM, "Ned Batchelder" <ned at nedbatchelder.com> wrote:
> On 11/27/13 2:40 PM, magnus.lycka at gmail.com wrote:
>> So, in the case of "a.b + x" I'm really just interested in a and x, not
b. So the (almost) whole story is that I do:
>>      # Find names not starting with ".", i.e a & b in "a.c + b"
>>      abbr_expr = re.sub(r"\.\w+", "", expr)
>>      names = compile(abbr_expr, '<string>', 'eval').co_names
>>      # Python 2.6 returns '_[1]' in co_names for list comprehension. Bug?
>>      names = [name for name in names if re.match(r'\w+$', name)]
>>      for name in names:
>>          if name not in allowed_names:
>>              raise NameError('Name: %s not permitted in expression: %s'
% (name, expr))
> I don't know of a better way to determine the real names in the
expression.  I doubt Python will insert a valid name into the namespace,
since it doesn't want to step on real user names.  The simplest way to do
that is to autogenerate invalid names, like "_[1]" (I wonder why it isn't

One possible alternative is to use the ast module to examine the parse tree
of the expression instead of the generated code object. Hard to say whether
that would be "better".
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20131127/5098adc9/attachment.html>

More information about the Python-list mailing list