Let's Talk About Lambda Functions!

Ian Bicking ianb at colorstudy.com
Fri Aug 2 16:32:41 EDT 2002


On Thu, 2002-08-01 at 17:31, John Roth wrote: 
> > >Unfortunately, that won't work. The word 'self' is not
> > >magic - using it doesn't convert a function to a method.
> > >
> > No, but making it a class attribute seems to do the magic
> > (which can also be modified with staticmethod and  classmethod).
> 
> Yes, but that's the exact problem. Methods become such by
> being directly under the class definition. Lambdas are not methods
> because they aren't directly under the class definition, and a
> generalized
> "def" also isn't directly under the class definition: it's within
> another method
> (or possibly list, tuple or dictionary definition.)

I don't think you are understanding how Python works here -- modules do
not get analyzed.  They get executed, and all the fancy stuff happens at
runtime. 

In this case, all the stuff indented underneath a class gets put in the
class attributes.  Just like: 
  def x(): return 1 
is equivalent to: 
  x = lambda : 1 
on a global level, they are also equivalent in class definitions. 

Methods *only* come to exist at runtime.  A method is created when you
access a class attribute which is a function. 

Right now there is no other way (I know of) to make a function into a
method (though it's easy to fake).  If there were such a way, I imagine
it would be a function (say, "method"), and you'd create a method by
calling method(instance, function).  So to make a method inside a
method, you'd do: 

# Note: hypothetical code 
class X: 
    def y(self): # y returns a method 
        def z(self): return 1 
        # z is not yet a method -- it's just a function 
        z = method(self, z) 
        return z 

You could also do (assuming nested scopes): 

class X: 
    def y(self): 
        def z(self): return 1 
        return lambda : z(self) 

Even with new-style objects, and different kind of methods
(staticmethods and classmethods), there's still only one way to define a
function, and it always defines a plain function.  

> That's the rub. You can have it one way or the other - either an
> anonymous 'def' found anywhere within a class is a function or a
> method, but it can't be either without some other syntax to specify
> which.

If you're going to be Pythonic, it will always be a function, never a
method.  Methods are just a kind of function currying, though, so it's
no big deal to create them manually. 

  Ian 






More information about the Python-list mailing list