Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an inline function that modifies a variable in Python?

Suppose I have a class that looks like this:

class Foo:
    def __init__(self, method):
        self.method = method

    def do_action(self):
        self.method()

and I want to instantiate it as follows:

some_var = False

def bar():
    # Modifies existing variable's value
    global some_var
    some_var = True
foo = Foo(bar)

how do I do that without having to define the bar() method? I've tried the following and it doesn't work.

foo = Foo(lambda: (some_var := True))

When I do this the IDE tells me there's an identifier expected. Thanks in advance!

EDIT: Thank you to those who answered, however I didn't really find exactly what I needed. Not sure if it's the best practice, but I ended up using python's exec and it works as intended:

foo = Foo(lambda: exec("some_var = True"))
like image 282
kguzek Avatar asked Jul 24 '26 19:07

kguzek


1 Answers

If the idea is to have bar be able to modify an instance attribute, have bar take the self parameter so do_action can tell it which instance it's operating on. You can't do a variable assignment inside a lambda, so use __setattr__:

class Foo:
    def __init__(self, method):
        self.method = method
        self.some_var = False

    def do_action(self):
        self.method(self)


foo = Foo(lambda self: self.__setattr__("some_var", True))
foo.do_action()
print(foo.some_var)  # True
like image 73
Samwise Avatar answered Jul 27 '26 08:07

Samwise



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!