Let's Talk About Lambda Functions!

Andreas Kostyrka andreas at kostyrka.priv.at
Wed Aug 14 08:41:43 EDT 2002


Am Fre, 2002-08-02 um 00.31 schrieb John Roth:

> In thinking about this, and following up on your other suggestion
> to use parens to delimit anonymous functions for clarity, we could
> use parens for functions, and brackets for methods. This wouldn't
> be the clearest syntax in the world, but Python currently distinguishes
> between the two by context.
What exactly should be the semantics of anonymous method? *wondering*

Python as such does not distinguish at all :)
Try this:

def func(a,b):
	a.x=b

class A:
	pass

A.method=func
a=A()
a.method(1)
print a.x

So obviously being defined in a class scope is not necessary for method.

Basically, what python does is to generate wrapper around a function
(when a function is fetched from the class dictionary), that binds the
first parameter of the function to the instance.

See:
>>> a.method
<bound method A.func of <__main__.A instance at 0x8160144>>
>>> a.method.im_func
<function func at 0x816081c>
>>> a.method.im_self
<__main__.A instance at 0x8160144>
>>> A.method.im_func
<function func at 0x816081c>
>>> A.method.im_self

So basically accessing a function object trough the class gives you an
unbound wrapper (this is done so, that the "method" can check if the
first parameter passed to it is of a correct type).
And when accessing a function trough the instance, you get a bound
method.

So basically depending upon which effect you want to get, you can do two
things with function objects (be it defs or lambdas):
a) stuff it in the class. Makes the function automatically a method:
>>> A.meth=lambda s: s.x
>>> a.meth()
1

b) if you want a nested function that can be passed around (no matter
which Python version), you can stick a self=self as a last parameter:

  def mymethod(self):
     ...
     innermethod=lambda self=self: self.value
     ...

Andreas





More information about the Python-list mailing list