6

I am a beginner in Python, and I would like to add a parameter to a callback, in addition to the self and the event. I have tried with lambda, but without success.
My code at the moment looks like this :

control = monitor(block, callback=self.model)  

And my model is :

def model(self, transaction)

I would like to have :

def model(self, file, transaction)   

file being a string parameter I would like to pass to my "model" I tried by changing the control line in :

control = monitor(block, lambda transaction, args=args:    callback=self.model(transaction, args)  

but this does not work, and it is getting too advanced but my python knowledge.
I get the following Error : "SyntaxError: lambda cannot contain assignment", I guess because of the = symbol.

Could you help me by explaining how I should proceed/what I am doing wrong ?

0

1 Answer 1

10

Many times, when you think about using lambda, it is best to use functools.partial() which performs currying (or curryfication). You can use

from functools import partial

def model(self, transaction, file=None):
    ...

control = monitor(block, callback=partial(self.model, file='foobar'))

To answer your comment below, if you really need a true function, you can design you own:

def callback(func, **kwargs):
    @functools.wraps(func)
    def wrapper(*a, **k):
        return functools.partial(func, **kwargs)(*a, **k)
    return wrapper

control = monitor(block, callback=callback(self.model, file='foobar'))
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this works, and answers the question. I just get a side issue since partial have no name attribute whereas callback does. I check for this parameter somewhere else in some external code that I will change accordingly...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.