Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #60634

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

References <6cdefe87-5703-4caf-91c0-b4a02674a1e5@googlegroups.com> <l75jhi$o7r$1@ger.gmane.org>
Date 2013-11-27 13:23 -0700
Subject Re: '_[1]' in .co_names using builtin compile() in Python 2.6
From Ian Kelly <ian.g.kelly@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.3318.1385583798.18130.python-list@python.org> (permalink)

Show all headers | View raw


[Multipart message — attachments visible in raw view] - view raw

On Nov 27, 2013 2:11 PM, "Ned Batchelder" <ned@nedbatchelder.com> wrote:
>
> On 11/27/13 2:40 PM, magnus.lycka@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
"_[0]"?)

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".

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

'_[1]' in .co_names using builtin compile() in Python 2.6 "magnus.lycka@gmail.com" <magnus.lycka@gmail.com> - 2013-11-27 11:40 -0800
  Re: '_[1]' in .co_names using builtin compile() in Python 2.6 Ned Batchelder <ned@nedbatchelder.com> - 2013-11-27 15:09 -0500
    Re: '_[1]' in .co_names using builtin compile() in Python 2.6 "magnus.lycka@gmail.com" <magnus.lycka@gmail.com> - 2013-11-28 03:17 -0800
  Re: '_[1]' in .co_names using builtin compile() in Python 2.6 Ian Kelly <ian.g.kelly@gmail.com> - 2013-11-27 13:23 -0700
  Re: '_[1]' in .co_names using builtin compile() in Python 2.6 Chris Kaynor <ckaynor@zindagigames.com> - 2013-11-27 12:44 -0800
  Re: '_[1]' in .co_names using builtin compile() in Python 2.6 Ned Batchelder <ned@nedbatchelder.com> - 2013-11-27 16:26 -0500
  Re: '_[1]' in .co_names using builtin compile() in Python 2.6 Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-11-27 22:08 +0000

csiph-web