Would Anonymous Functions Help in Learning Programming/Python?

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Mon Sep 24 17:26:38 CEST 2007


NickC a écrit :
> On Sep 24, 9:16 pm, Bruno Desthuilliers <bruno.
> 42.desthuilli... at wtf.websiteburo.oops.com> wrote:
>> Matthew Woodcraft a écrit :
>>> One reason for the different syntax is that functions, unlike most
>>> other objects, know their own names (which can be shown in tracebacks
>>> and the like).
>> Nope. They know *one* of their names - the one they've been given when
>> first instanciated. Which may or not be the name used to get at them...
> 
> That's exactly the point - a function may be given many names through
> the assignment statement, just like any other data value. However, the
> *first* name given to a function (the one in the def statement) is
> special, as that is the name the function knows *itself* by.
> 
"knows itself by" ? Really ?-)

 >>> def toto(level):
...     print "toto %s" % level
...     if level == 0: print "done"
...     else: toto(level-1)
...
 >>> toto(3)
toto 3
toto 2
toto 1
toto 0
done
 >>> tutu = toto
 >>> def toto(level):
...     print "YADDA YADDA"
...
 >>> tutu(3)
toto 3
YADDA YADDA
 >>>


> While a function *can* be treated like any other piece of data once
> you have a reference to one, the original statement does a lot more
> than a normal assignment does:

Indeed. But :

>   - being within the scope of a function significantly alters name
> binding and lookup

Runtime stuff and 'locals' parameters of te function object initializer 
AFAICT.

>   - return statements and yield statements are meaningful only within
> the scope of a function

s/"within the scope"/"in the code object"/, I'd say... Look at the 
signature of the function object's initializer, it takes a code object.

Please some guru correct me if I'm wrong, but AFAICT, you can have all 
this working without the def statement itself (even if it's quite enough 
of a boring work to justify the existence of the def statement).

Anyway, the OP suggestion was to turn the statement into an expression 
(à la javascript), not to get rid of it.

>   - you can attach decorators to a function definition

@decorators are just syntactic sugar for HOFs. If you want to apply a 
decorator do a lambda, you don't need this syntax - just pass the lambda 
as a param to the decorator.

>   - you can include a docstring in a function definition

And you can add it afterwards too:

>>> toto.__doc__ is None
True
>>> toto.__doc__ = "yadda"
>>> toto.__doc__
'yadda'


Don't get me wrong, I'm not saying the def statement is useless. Just 
that the reasons why this statement exists have very few to do with your 
arguments here.



More information about the Python-list mailing list