Search code examples
pythonfunctionhttpcallback

How to pass arguments to a callback function in Python?


I want to make my code Async for HTTP calls, since the whole program stops while the call is being made.

I took a look at grequests and couldn't figure it out, same for asyncio

this is the current sync version of the code:

myvar1 = class_object()

response = requests.get(myvar1.url)

if response.status_code == 200:
    myvar1.accept()

I would like to do the following instead:

def myfunction:

    request.get(myvar1.url,callbackfunction(response,myvar1))

    return None

def callbackfunction(response,myvar1):

    if response.status_code == 200:
        myvar1.accept()

I can successfully pass a callback function to the request, the question is how to pass arguments to that callback.

Basically, the goal is to execute a method of the passed argument of the callback function.


Solution

  • Lets make a partial function:

    
    def myfunction(var, func):
    
        request.get(var.url, callback =  func)
    
    
    def callbackfunction(response, var):
    
        if response.status_code == 200:
            var.accept()
    
    # Now make a partial function to wrap callbackfunction
    def wrapper(var):
        def callback(response):
            callbackfunction(response, var)
        return callback
    
    myvar1 = class_object()
    
    myfunction(myvar1, wrapper(myvar1))
    

    So, requests.get() will eventually call func(response) which in fact will be callback(response) which calls callbackfunction(response, myvar1)