Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding parameter to python callback

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 ?

like image 415
user1654361 Avatar asked Dec 10 '16 17:12

user1654361


People also ask

Can callbacks have parameters?

Yes. The print( ) function takes another function as a parameter and calls it inside. This is valid in JavaScript and we call it a “callback”. So a function that is passed to another function as a parameter is a callback function.

What are callback parameters?

A callback function, also known as a higher-order function, is a function that is passed to another function (let's call this other function “otherFunction”) as a parameter, and the callback function is called (executed) inside the other function.

Can we pass a parameter in a Python function?

Information can be passed into functions as arguments. Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.

How do I call a callback function in Python?

In the Parallel Python Module, the submit function is known as the callback function. The callback function acts as an argument for any other function. The other function in which the callback function is an argument calls the callback function in its function definition.


Video Answer


1 Answers

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'))
like image 169
Gribouillis Avatar answered Oct 23 '22 12:10

Gribouillis