Property setter and lambda question

Thomas Jollans t at jollybox.de
Mon Jul 11 12:23:39 EDT 2011


On 07/11/2011 05:54 PM, Anthony Kong wrote:
> Hi, all,
> 
> This question is in the same context of my two earlier questions. This
> question was raised by some python beginners, and I would like to check
> with the list to ensure I provide a correct answer.
> 
> Here is a code snippet I used to demonstrate the keyword *property*:
> 
> 
> class A(object):
> 
>     def __init__(self):
>         self.__not_here = 1
> 
>     def __get_not_here(self):
>         return self.__not_here
> 
>     def __set_not_here(self, v):
>         print "I am called"
>         self.__not_here = v
> 
>     not_here = property(lambda self: self.__get_not_here(), lambda self,
> v: self.__set_not_here(v))
>     # not_here = property(lambda self: self.__not_here, lambda self, v:
> self.__not_here = v)
> 
> So the question: is it possible to use lambda expression at all for the
> setter? (As in the last, commented-out line)
> 
> Python interpreter will throw an exception right there if I use the last
> line ('SyntaxError: lambda cannot contain assignment'). I'd use pass a
> setter method anyway.  
> 
> What is your preferred solution?

No, a lambda can only contain an expression, not a statement. This is
not C, assignments are not expressions.

As to what I would do:
There's really no need to use lambdas at all here:

class A(object):
    def __init__(self):
        self.not_here = 1
    def __get_not_here(self):
        return self.__not_here
    def __set_not_here(self, val):
        self.__not_here = val
    not_here = property(__get_not_here, __set_not_here)

My favourite way to create properties is of course with decorators:

class A(object):
    def __init__(self):
        self.not_here = 1

    @property
    def not_here(self):
        return self.__not_here

    @not_here.setter
    def not_here(self, val):
        self.__not_here = val



More information about the Python-list mailing list