Skip to content Skip to sidebar Skip to footer

How Can I Create Chain Of Callbacks In Python?

In javascript I can do following: var some = 100; var param1 = 1; func1(param1, function(res1) { var param2 = res1 + some; func2(param2, function(res2) { // ...

Solution 1:

Pass functions as arguments.

some = 100defcallback1(res1):
    param2 = res1 + some
    func2(param2, callback2)
defcallback2(res2):
    ...

param1 = 1
func1(param1, callback1)

Solution 2:

I see that you tagged asynchronous as well. Python is NOT asynchronous. But python functions are also first class objects just like javascript and php. So, you can do the same thing in python as well.

deffunc1(data, nextFunction = None):
    print data
    if nextFunction:
        nextFunction()

deffunc(data, nextFunction = None):
    print data
    nextFunction(data * 10)

func(1, func1)

Output

1
10

Inline function definitions are restricted in python but it is still possible with lambda functions. For example,

data = ["abcd", "abc", "ab", "a"]
printsorted(data, key = lambda x: len(x)) # Succinctly written as key = len

Output

['a', 'ab', 'abc', 'abcd']

Solution 3:

Functions are first class objects in Python, and you can nest them as well.

EG:

#!/usr/local/cpython-3.3/bin/python

some = 100

param1 = 1deffunc1(param1, function):
    param2 = res1 + some;
    deffunc2(param2, function):
        pass
    func2(param2, function)

Solution 4:

Decorators are just syntactic wrappers for "thing that can execute arbitrary code before and after another function." That's what you're doing with a callback, and hey: flat is better than nested.

deffunc1(fn):
    defwrapped(arg):
        return fn(arg+1)
    return wrapped

deffunc2(fn):
    defwrapped(arg):
        return fn(arg+2)
    return wrapped

@func1@func2deffunc3(x):
    return x + 3print(func3(1))
#prints 7

Post a Comment for "How Can I Create Chain Of Callbacks In Python?"