G
G
germn2013-11-16 08:24:52
Python
germn, 2013-11-16 08:24:52

How to implement a chain of callbacks in python?

In javascript I can do like this:

var some = 100;

var param1 = 1;
func1(param1, function(res1) {
    
    var param2 = res1 + some;
    func2(param2, function(res2) {
        // ...
    });
});

In php I can do like this:
$some = 100;

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

How to do it in python?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
stepank, 2013-11-16
@germn

in python, there are only lamba as anonymous functions, which have very strict restrictions, for example, that their body can contain only one expression, i.e. in plain language - there can't be very much logic inside a lambda. therefore, for more complex structures, you need to create named functions, for example:

some = "hello"
def func_1():
    print some
    one_more = "world"
    def func_2():
        print some, one_more
        def func_3():
            print "hello world"
        return func_99("bla-bla", func_3)
    return func_100("bla-bla", func_2)

There are various options for avoiding large nesting, but this does not apply directly to the topic of the question. besides, if you are working with Twisted, then of course you need to learn Deferred, because without them, this framework is nowhere at all. I don’t know about Tornado, probably there is some kind of similar mechanism. if you do not use any of the above frameworks, then the Deferred concept itself still makes sense to study, because. there are implementations not tied to these frameworks, but with the help of Deferred, working with chains of callbacks becomes much more convenient

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question