I am dealing widgets and signals and I want to bind a signal to a certain callback. Since I don't really need to create a named callback function in the case of interest, I am defining it as a lambda function. However, the way it integrates with other classes is best described by the following minimal working example:
class Foo():
def parse(self, what):
self.bar = what
foo = lambda x = Foo(): (x.parse("All set"), x)[-1]
print(foo().bar)
'All set'
The lambda function needs to instantiate a class, call one of its members to parse a string and change its internal state, and return the instantiated class. The only way to do this that I can think of at the moment is as shown in the above example: pass the instance as the default argument, create a list where the first element is the call to the method and the second is the instance itself, then select the last element.
Is there a more pythonic and elegant way of obtaining the same result?
EDIT: A few caveats: In the actual code the class Foo is defined in other modules, and I'm passing the lambda as an argument to another function, hence why I don't really need to name the callback. Indeed, what I actually have is something that looks like
widget.bind( 'some_signal', lambda x = Foo(): (x.parse("All set"), x)[-1] )
Aucun commentaire:
Enregistrer un commentaire