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"))
some_varactually supposed to be? Your examplebaris a no-op sincesome_varis a local variable.some_varis a local/global variable, and if you really, really want to do something like this, you can addnonlocal some_varorglobal some_var(which every is appropriate) tobar. 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?barwould suffice but I'll add in a declaration.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.