Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Lambda Mutability

class TestClass(object):
    def __init__(self):
        self.value = 100
        self.x = lambda: self.value.__add__(100)
        self.run()

    def run(self):        
        self.x()
        print self.value

t = TestClass()

#Output: 100

I would like to able to define a lambda function such as the one in TestClass and have it alter an instance variable. It would seem that the way the lambda is constructed means that it does not modify the original value. I suspect that this to do with Python's reference strategy which I do more or less understand.

So accepting the flaws in what I have done, is there a similar way to get similar functionality? I ultimately need to define many methods like x and intend to keep them in a dictionary as they will form a simple instruction set. As far as I can tell I need either to use lambdas or exec to do what I want.

like image 815
sheepez Avatar asked May 05 '26 22:05

sheepez


1 Answers

__add__ is not inplace, so the return value of TestClass.x is self.value + 100, but self.value is not altered. Try this:

import random
HATE_LAMBDAS = random.choice(True, False)
class TestClass(object):
    def __init__(self):
        self.value = 100
        if HATE_LAMBDAS:
            def x():
                self.value += 100
            self.x = x
        else:
            self.x = lambda: setattr(self, "value", self.value + 100)
        self.run()

    def run(self):        
        self.x()
        print self.value

t = TestClass()

#Output: 200

Use the setattr to increment the value while still using a lambda. Beware however, lambda's in python are one of its worst features. However, both methods work.

Edit

Just remebered something that you might find usefull! The standard library has a module called operator which implements standard operators as functions. If you plan on using lambdas a lot, you might like to investigate it.

like image 183
BluePeppers Avatar answered May 08 '26 12:05

BluePeppers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!