annonymous functions -- how to

Bengt Richter bokr at oz.net
Thu May 5 13:13:01 EDT 2005


On Thu, 05 May 2005 07:45:33 -0400, Peter Hansen <peter at engcorp.com> wrote:

>Jason Mobarak wrote:
>> What's wrong with:
>> 
>> def blah():
>>   def _ (a, b, c):
>>     a = a + 2
>>     print "stmt 2"
>>     return a+b/c
>>   return doSomethingWith(_)
>> 
>> It's basically "anonymous", it just uses a name that you don't care
>> about. AFAIK, it can be immediately clobbered later if need be.
>> Otherwise, the function shouldn't be anonymous.
>
>Or even better:
>
>def blah():
>    def doJasonsAlgorithm(a, b, c):
>       a = a + 2
>       print "stmt 2"
>       return a+b/c
>    return doSomethingWith(doJasonsAlgorithm)
>
>That way you've got reasonably self-documenting code, and don't have to 
>face an annoyed maintainer saying "what a jerk: he didn't comment this 
>or even give it a useful name... idiot... grumble grumble."
>
>I doubt there's a valid usecase for a "anonymous" function that has more 
>than a line or two.  Personally, I don't think there's a good usecase 
>for an anonymous function longer than one line...
>
Yes, but only the BDFL can outlaw things on that kind of basis ;-)

My post was just to play with "anonymous" a little, not to motivate
more examples of strange call layering and dynamic execution of defs
that don't change etc. ;-)

BTW, I view a def as a kind of assignment statement with the target restricted
to a local bare name. I.e.,

    def foo(): pass   # def <restricted assignment target>():pass

So why have this form of assignment? And why restrict it to a bare name, even
if you want to keep the def for mnemonic convention to use as usual?

I.e., why not loosen def to allow e.g.

    def MyClass.method(self): pass
or
    @staticmethod
    def MyClass.square(x): return x*x

or
    def fdict['sqr'](x): return x*x

Well, I can see a reason not to do the last that way. It would be much clearer using
an anonymous def, e.g.,

    fdict['sqr'] = def(x): return x*x

And then you can say lambda is fine for that, except for the limitation
that the body be just an expression. Then you might ask, why not bend that a little? E.g.,

    fdict['sqrt'] = def(x):
	if x < 0: raise ValueError, 'x must be non-negative, not %r' %x
        return math.sqrt(x)

And then, why not allow an anonymous defs as expressions anywhere expressions can go?
(indentation problems are actually easy to overcome).

Anyway, in general, I'd rather be persuaded than forced ;-)

Regards,
Bengt Richter



More information about the Python-list mailing list