views:

564

answers:

1

I have smth like this:

class X():
    def __init__(self):
        self.__name = None

    def _process_value(self, value):
        # do smth
        pass

    def get_name(self):
        return self.__name

    def set_name(self, value):
        self.__name = self._process_value(value)

    name = property(get_name, set_name)

Can I replace get_name and set_name using lambda functions?

I've tried this:

name = property(lambda self: self.__name, lambda self, value: self.__name = self.process_value(value))

but compiler doesn't like my setter function.

+4  A: 

Your problem is that lambda's body must be an expression and assignment is a statement (a strong, deep distinction in Python). If you insist on perpetrating lambdas you'll meet many such cases and learn the workarounds (there's usually one, though not always), such as, in this case:

name = property(lambda self: self.__name, 
                lambda self, value: setattr(self, 
                                            '_X__name',
                                            self.process_value(value)))

i.e. use the built-in setattr (which is a function and thus acceptable in a lambda's body) rather than assignment (which is a statement and thus unacceptable in a lambda's body).

Edit: You also need to perform the name-mangling for the dual-underscore attribute manually (changing __name to _X__name as you're in class X) where the attribute name is presented as a quoted string, as it must be in setattr, as the Pyhon compiler only does the name mangling in question for suitable identifiers, not for string literals.

Alex Martelli
Great! Thank you, Alex.
zdmytriv
I have one more issue there. setattr works only for "_name" not "__name".
zdmytriv
Ah yes, you need to manually perform the mangling as it's a quoted-string -- let me edit accordingly!
Alex Martelli