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


Groups > comp.lang.python > #3636

Re: List comprehension vs filter()

References <BANLkTin4KMcoWzfH64Eu=+sD9=M3TaAu2A@mail.gmail.com>
Date 2011-04-20 13:20 +1000
Subject Re: List comprehension vs filter()
From Chris Angelico <rosuav@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.606.1303269624.9059.python-list@python.org> (permalink)

Show all headers | View raw


On Wed, Apr 20, 2011 at 1:10 PM, Chris Angelico <rosuav@gmail.com> wrote:
> type=lst[0]["type"].lower()
>
> lst=filter(lambda x: x["type"].lower()==type,lst) # Restrict to that one type

After posting, I realised that "type" is a built-in identifier, and
did a quick variable name change to "posttype" which shouldn't have a
problem. Now, the filter/lambda line bombs with NameError: global name
'posttype' is not defined. Could it be that the lambda is ignoring
local variables? If that's so, then it would have been comparing the
dictionary entry against the built-in type <type>, which will of
course never match. That could also explain why running the same code
as a standalone .py file works (variables defined in the body of a .py
file are global by default, if I have this correct). But why would
lambda bind to global variables but not local ones?

The Python code is being called from C as:

PyObject *v=PyRun_StringFlags(code,Py_file_input,py_globals,locals,0);

where py_globals and locals are dictionaries, code is a const char *
with the code.

I have Lucia di Lammermoor singing in the background, and I think I'll
be going as mad as she soon! This is so weird...

Chris Angelico

Back to comp.lang.python | Previous | Next | Find similar


Thread

Re: List comprehension vs filter() Chris Angelico <rosuav@gmail.com> - 2011-04-20 13:20 +1000

csiph-web