List comprehension vs filter()

Chris Angelico rosuav at gmail.com
Tue Apr 19 23:20:21 EDT 2011


On Wed, Apr 20, 2011 at 1:10 PM, Chris Angelico <rosuav at 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



More information about the Python-list mailing list