V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
lbfeng
V2EX  ›  问与答

Python twisted chian 实在没看懂这段代码

  •  
  •   lbfeng · 2018-08-08 04:01:07 +08:00 · 1119 次点击
    这是一个创建于 2303 天前的主题,其中的信息可能已经有所发展或是发生改变。
    from twisted.internet import defer
    
    def status(*ds):
        return [(getattr(d, 'result', "N/A"), len(d.callbacks)) for d in ds]
    
    
    def b_callback(arg):
        print "b_callback called with arg =", arg
        return b
    
    
    def on_done(arg):
        print "on_done called with arg =", arg
        return arg
            
    a = defer.Deferred()
    b = defer.Deferred()
    
    a.addCallback(b_callback).addCallback(on_done)
    
    status(a, b) # [('N/A', 2), ('N/A', 0)]
    
    a.callback(3) # b_callback called with arg = 3
    
    status(a, b) # [(<Deferred at 0x7f219e4117a0>, 1), ('N/A', 1)]
    
    b.callback(4) # on_done called with arg = 4
     
    status(a, b) # [(4, 0), (None, 0)]
    

    a.callback(3) 之后 b 也有了 on_done callback。这里没明白。b.callback(4)之后 a 的 on_done 也执行了,但只输出了一个 on_done called with arg = 4,且 b 的 result 是 None 不是 4 ??

    1 条回复    2018-08-09 02:31:26 +08:00
    lbfeng
        1
    lbfeng  
    OP
       2018-08-09 02:31:26 +08:00
    我自问自答吧。。。

    `b` get a callback function after `a.callback(3)`. By checking the source code( https://github.com/twisted/twisted/blob/twisted-18.7.0/src/twisted/internet/defer.py#L438). It seems that `b` is appended an "a is waiting for b to fire" callback. Chain would stop here since function `b_callback` return deferred `b`, and `b` would be the result of `a`. Note: if result is a value instead of a deferred object, chain will continue.

    `b.callback(4)` passes `4` to `a`'s next callback as an argument. `b` get a `None` as a result. The chain continues.
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   5361 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 22ms · UTC 08:17 · PVG 16:17 · LAX 00:17 · JFK 03:17
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.