Would Anonymous Functions Help in Learning Programming/Python?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Fri Sep 21 21:17:48 EDT 2007


On Fri, 21 Sep 2007 22:07:55 +0000, Cristian wrote:

> True, there is lambda, but that is very limited. It might be useful for
> key arguments, but not much else.

No, lambda is useful for anything that any other function is useful for, 
provided that you can write it as a single expression and not need to use 
statements. In other words, a lambda function can do anything anything 
any other function can, just less conveniently.

(To pick one example at random, you can use print with lambda:
http://northernplanets.blogspot.com/2006/07/python-using-print-with-lambda.html 
and while it is easy it isn't exactly convenient.)

And that's basically why function definitions have the syntax they do, 
because trying to hammer a multi-line function definition into a single 
expression is painful.


> It doesn't solve the teaching problem
> of "See, functions are just like any other data type. You can assign it
> to a variable." 


Is their interactive interpreter broken?


>>> def parrot(colour='red'):
...     return "I'm a parrot with %s plumage." % colour
...
>>> bird = parrot # note the lack of brackets
>>> type(bird)
<type 'function'>
>>> bird('green')
"I'm a parrot with green plumage."


Or using lambda:


>>> parrot = lambda colour: "I'm a parrot with %s plumage." % colour
>>> parrot("purple")
"I'm a parrot with purple plumage."



> It would be a footnote if it's mentioned at all. My hope
> is to subtly reinforce the notion that functions are data and can be
> passed around. The current function declaration doesn't help with this.

Some things just need to be learnt. I'm in favour of making languages 
easy for newbies to learn, but making function and method definitions 
harder to use just so newbies will be given a subtle reminder of 
something that 80% of them will never notice or use anyway is a bad 
trade-off.


> Creating a function and assigning it to a name is exactly what Python
> does, why not have it come out in the syntax? It's not necessary, yes,
> but I think it would be helpful for teaching purposes.

If people don't get it when you EXPLICITLY show them that functions are 
first-class objects, how do you expect them to notice it on their own 
based on the IMPLICIT similarities in syntax?




-- 
Steven.



More information about the Python-list mailing list