lambda requirements
David Goodger
dgoodger at bigfoot.com
Mon Jul 3 10:17:07 EDT 2000
Lambda expressions don't have access to the local namespace. Declaring
_list2 as global gets around this problem, but in an "unclean" way (note
that _list1 doesn't need to be global, as it's not accessed inside the
lambda). A cleaner way to implement the lambda (without globals, or
"_"-prefixed local variables) is as follows:
_onlylist1 = filter(lambda x, l=list2: x not in l, list1)
"l" is bound to "list2" when the lambda expression is evaluated (when the
local namespace *is* accessible), which carries through to when the
resulting anonymous function is executed by filter (when
SymmetricDifference's local namespace is *not* accessible).
--
David Goodger dgoodger at bigfoot.com Open-source projects:
- The Go Tools Project: http://gotools.sourceforge.net
(more to come!)
on 2000-07-03 08:41, Wolfgang Thaemelt (wolfgang.thaemelt at orsoft.de) wrote:
> Running the script:
>
> #----------------------------------------- begin of script
> def SymmetricDifference(list1, list2):
> # global _list1
> # global _list2
>
> _list1 = list1
> _list2 = list2
>
> _onlylist1 = filter(lambda x: x not in _list2, _list1)
>
> return _onlylist1
>
> if __name__ == '__main__':
> a = [1,2,3,4,5]
> b = [3,4,5,6,7]
> x = SymmetricDifference(a,b)
>
> print x
> #---------------------------------------- end of script
>
> gives the error:
>
> Traceback (innermost last):
> File "E:\up\000701\symmdiff.py", line 16, in ?
> x = SymmetricDifference(a,b)
> File "E:\up\000701\symmdiff.py", line 9, in SymmetricDifference
> _onlylist1 = filter(lambda x: x not in _list2, _list1)
> File "E:\up\000701\symmdiff.py", line 9, in <lambda>
> _onlylist1 = filter(lambda x: x not in _list2, _list1)
> NameError: _list2
>
> If the comment characters "#" are removed from the "global" statements
> everything works fine.
>
> Is there some requirement on a lambda violated in the script?
More information about the Python-list
mailing list