__init__ as a lambda

Steven D'Aprano steve-REMOVE-THIS at cybersource.com.au
Thu Aug 5 05:18:39 CEST 2010


On Wed, 04 Aug 2010 12:58:18 -0700, Eric J. Van der Velden wrote:

> Hello,
> 
> Suppose
> 
> class C:
>  def __init__(self,name):self.name=name
> 
> I was wondering if I could make the __init__ a lambda function,

Of course you can. Lambdas aren't special types of functions, they are 
*syntax* for creating a function consisting of a single expression, and 
your __init__ function is a single expression.

These two are almost identical:

def spam(a, b):
    return a+b


spam = lambda a, b: a+b

The only(?) differences are spam.func_name or spam.__name__.


> but
> 
> class C:
>  __init__=lambda self,self.name:None
> 
> and then later,
> 
> C('Hello')
> 
> does not work; the first argument, self, is assigned all rigth, but you
> cannot write the second argument with a dot,  self.name . 

That gives a syntax error no matter whether you use it in a lambda form 
or an ordinary function:

>>> def f(self,self.name):
  File "<stdin>", line 1
    def f(self,self.name):
                   ^
SyntaxError: invalid syntax


So the problem has nothing to do with lambda. What you want is:

lambda self: self.name = None

but of course that doesn't work either, because self.name = None is not 
an expression, it's a statement. So:


class C:
    __init__ = lambda self: setattr(self, 'name', None)


But don't do this. Seriously. Just because it is syntactically valid and 
does what you want, doesn't mean you should do it. Unless you have really 
good reason, and saving a single line of source code is a *bad* reason, 
just stick to the standard idiom that everyone can read without going 
"WTF is this guy doing this for???".

class C:
    def __init__(self):
        self.name = None




-- 
Steven



More information about the Python-list mailing list