List comprehension vs filter()

Chris Angelico rosuav at
Wed Apr 20 10:36:08 CEST 2011

On Wed, Apr 20, 2011 at 5:16 PM, Tim Roberts <timr at> wrote:
> It's because, unlike some other languages (like Pascal), Python doesn't
> have infinitely recursive nested namespaces.  Glossing over details, there
> is a global namespace, and there is a local namespace.  A new function gets
> a new local namespace.  "posttype" is part of the local namespace of the
> outer function, but it's not part of the local namespace of the lambda.

Okay, well that saves me from going insane anyhow! (Although it may be
too late to save me from that.) I skimmed your email and then tried to
explain it all to my boss, who has some programming experience but
only rudimentary Python, and after ten or fifteen minutes we concluded
that I needed to put some comments in the code.

> You can solve this through the common lamba idiom of a closure:
> lst=filter(lambda x,posttype=posttype: x["type"].lower()==posttype,lst)

Seems a little odd, but sure. I guess this means that a function's
default arguments are evaluated in the parent context, but the body is
evaluated in its own context?

>From what I understand, though, from __future__ import nested_scopes
became a permanent part of the language long before 2.6.6, and PEP 227
describes this exact situation of lambda functions: gives an example involving
Tkinter. Unfortunately googling for 'python nested scope' mainly turns
up old information from 2.1 and thereabouts; has anything changed
since then?

Infinitely-nested scopes is definitely how I, as a programmer, tend to
think about my code. Any place where the computer's interpretation of
the code differs from mine is a place where either the computer needs
to change its thinking, or I do. And it's usually easier to change me,
except that I use so many languages. :)

Chris Angelico

More information about the Python-list mailing list