Mikhail Gerasimov
Mikhail Gerasimov

Reputation: 39576

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) {
        // ...
    });
});

In php same:

$some = 100;

$param1 = 1;
func1($param1, function($res1) use ($some) {

    $param2 = $res1 + $some;
    func2($param2, function($res2) {
        // ...
    });
});

How can I do same thing in python?

................................................

Upvotes: 1

Views: 2013

Answers (4)

roippi
roippi

Reputation: 25974

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.

def func1(fn):
    def wrapped(arg):
        return fn(arg+1)
    return wrapped

def func2(fn):
    def wrapped(arg):
        return fn(arg+2)
    return wrapped

@func1
@func2
def func3(x):
    return x + 3

print(func3(1))
#prints 7

Upvotes: 1

dstromberg
dstromberg

Reputation: 7187

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 = 1

def func1(param1, function):
    param2 = res1 + some;
    def func2(param2, function):
        pass
    func2(param2, function)

Upvotes: 1

falsetru
falsetru

Reputation: 369364

Pass functions as arguments.

some = 100

def callback1(res1):
    param2 = res1 + some
    func2(param2, callback2)
def callback2(res2):
    ...

param1 = 1
func1(param1, callback1)

Upvotes: 3

thefourtheye
thefourtheye

Reputation: 239623

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.

def func1(data, nextFunction = None):
    print data
    if nextFunction:
        nextFunction()

def func(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"]
print sorted(data, key = lambda x: len(x)) # Succinctly written as key = len

Output

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

Upvotes: 2

Related Questions