pinnwand

bpaste has migrated platforms. We now support self removal of pastes and will automatically import pastes from our old software for the following 2 months (that is, until the end of november 2014).

If you have any pastes you'd like to preserve please visit their URLs and they will be automatically imported with no expiry.

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

 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