List comprehension vs filter()

Ian Kelly ian.g.kelly at gmail.com
Wed Apr 20 10:44:58 EDT 2011


On Wed, Apr 20, 2011 at 4:41 AM, Peter Otten <__peter__ at web.de> wrote:
> The assignment writes to the local namespace, the lambda function reads from
> the global namespace; this will only work as expected if the two namespaces
> are the same:
>
>>>> exec """type = 42; print filter(lambda x: x == type, [42])""" in {}, {}
> []
>>>> ns = {}
>>>> exec """type = 42; print filter(lambda x: x == type, [42])""" in ns
> [42]

That must be a quirk of exec, because it works just fine without using
exec, both in and out of functions, either from the interactive
interpreter or from a script:

Python 2.7.1 (r271:86832, Apr  2 2011, 19:44:19)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def f():
...     t = 42
...     print filter(lambda x: x == t, [42])
...
>>> f()
[42]
>>> t = 43
>>> print filter(lambda x: x == t, [43])
[43]

So, the question for the OP:  Is this file being run with execfile?

Cheers,
Ian



More information about the Python-list mailing list