4

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"))
4
  • You might need to include more code. What's some_var actually supposed to be? Your example bar is a no-op since some_var is a local variable. Commented Aug 1, 2021 at 19:58
  • Assuming some_var is a local/global variable, and if you really, really want to do something like this, you can add nonlocal some_var or global some_var (which every is appropriate) to bar. But this question really sounds like an XY problem. Could you elaborate on why you want to add a method to an object that modifies a local/global variable? Commented Aug 1, 2021 at 20:11
  • @Samwise It's supposed to change the value of an existing global variable. I thought the comment in the bar would suffice but I'll add in a declaration. Commented Aug 1, 2021 at 20:11
  • 3
    oh that's extremely gross, you'd have to use globals() to be able to modify that inside a lambda. Don't do it IMO. Global variables are bad enough without doing unnecessarily weird shenanigans like this. Commented Aug 1, 2021 at 20:12

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.