List comprehension vs filter()
timr at probo.com
Wed Apr 20 09:16:57 CEST 2011
Chris Angelico <rosuav at gmail.com> wrote:
>On Wed, Apr 20, 2011 at 1:45 PM, Chris Rebert <clp2 at rebertia.com> wrote:
>> Built-ins aren't quite the same as globals, but essentially yes:
>Sure. That might explain some of the weirdness, but it doesn't explain
>why things were still weird with the variable named posttype.
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.
You can solve this through the common lamba idiom of a closure:
lst=filter(lambda x,posttype=posttype: x["type"].lower()==posttype,lst)
Tim Roberts, timr at probo.com
Providenza & Boekelheide, Inc.
More information about the Python-list