fp/lambda question

Alex Martelli aleax at aleax.it
Sat Apr 13 03:58:34 EDT 2002


Jozef wrote:

> I was reading on functional programming in Python and wanted to test
> myself by writing a function:
> 
> functional_euler = lambda n: \
> len(filter(lambda i: gcd(i, n) == 1, range(1, n + 1)))
> 
> (gcd is the greatest common divisor function). It gives the following
> error: <stdin>:1: SyntaxWarning: local name 'n' in 'lambda' shadows use of
> 'n' as global in nested scope 'lambda'
> 
> I am not really sure even what this means... does lambda create a new
> scope or something? Is there another way to write this?

You're clearly using Python 2.1.something and don't have a:

    from __future__ import nested_scopes

at the very top of your module.  Therefore, the Python compiler does
not give you lexically nested scopes but does warn you about "shadowing"
of locals vs global nested-scope identifiers -- i.e., spots where
lexically nested scopes will change your program's semantics when
you enable them.

Either insert the 'from __future__', or move to Python 2.2.1 -- or both.

Yes, lambda (like all other function definitions) does create a new
scope.  List comprehensions don't, and they're just as 'fp' -- indeed,
Python copied them right from one of the "functionalest" programming
languages to be reasonably widespread, Haskell, just adjusting the
syntax a little bit (more keywords, less punctuation).

I like FP a lot, and I practise it -- but I eschew lambda in Python
in most cases: it's limited and goes much against the grain of the
language.  All it boils down to is, give your functions a name -- in
most cases a well-chosen name will clarify your code.  E.g.,

def relatively_prime(a, b): return gcd(a, b) == 1

and so on...


Alex




More information about the Python-list mailing list