1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
from __future__ import print_function

from twisted.internet import reactor, task
from twisted.internet.defer import inlineCallbacks, returnValue, Deferred

@inlineCallbacks
def get(mydict, key):
    """
    Deferred subscripting. Imagine that, instead of doing this in memory,
    we called over the network or something
    """

    # wait for a little (simulate network stuff etc., and let callbacks be
    # attached to the deferred we return)
    yield task.deferLater(reactor, 0, lambda *args, **kwargs: None, (), {})
    returnValue(mydict[key])

@inlineCallbacks
def getdefault(mydict, key, default):
    try:
        val = yield get(mydict, key)
    except LookupError:
        returnValue(default)
    else:
        returnValue(val)

getdefault([1], 0, None).addCallback(print)
getdefault([], 0, None).addCallback(print)

reactor.run() # actually execute all deferreds, and then loop forever

This paste never expires. View raw. Pasted through import.