Would Anonymous Functions Help in Learning Programming/Python?

Bryan Olson fakeaddress at nowhere.org
Sat Sep 22 16:30:05 EDT 2007


Paul Rubin wrote:
> Bryan Olson <fakeaddress at nowhere.org> writes:
>> chris.monsanto at gmail.com wrote:
>>> There are already anonymous functions in Python.
>>> lambda x, y, z: x + y + z
>>> is the same as:
>>> def _(x, y, z): return x + y + z
>> They are the same only in special cases:
>>      The special identifier "_" is used in the interactive
>>      interpreter to store the result of the last evaluation...
> 
> I'm not sure what Chris was really getting at, 

I was big-time unsure. At first, I thought Chris's latter
form to be equivalent to a pass statement. I've long used
the Python convention of assigning throw-away values to '_',
and I was under the mistaken impression Python defined _
as a discard target.

When I looked it up, I was surprised to find that my
understanding of the _ variable was wrong, and shocked that
there really is an interesting context where Chris's claim
has a strong case.


> since among other
> things lambda:... is an expression while def... is a statement.

True fact, but note that one form of statement is an expression.

> But Python certainly has anonymous functions without lambda:
> 
>    def compose(f,g):
>      def h(*a, **k):
>        return f(g(*a, **k))
>      return h
> 
>    x = compose(math.sin, math.cos)(1.0)
> computes sin(cos(1.0)) where a function equivalent to 
>   lambda x: sin(cos(x))
> is constructed and used without being bound to a symbol.

How anonymous is that function when we can see that its name is 'h'?

     import math

     f = compose(math.sin, math.cos)
     print f.__name__

Am I making a bogus argument? Kind of. Most authors of "anonymous"
works do in fact have real names. The term really means that they
entered the context at issue dissociated from their given name.
Nevertheless, def is never a real anonymous function constructor.

If our concern is Python's suitability for studying principles of
programming, I think I'm on stronger ground. Python is great for
getting things done. It is easy to learn in the sense of learning
to to use if for practical tasks. Python's actual semantics are not
as neat and clean as some other languages.


-- 
--Bryan



More information about the Python-list mailing list