[Twisted-Python] inlineCallbacksDecorator
Maarten ter Huurne
maarten at treewalker.org
Sun Jun 7 00:18:52 EDT 2009
On Sunday 07 June 2009, Terry Jones wrote:
> So I wrote a decorator specifically for inlineCallbacks decorated
> functions:
>
> from twisted.internet import defer
>
> def inlineCallbacksDecorator(callback, errback=defer.passthru):
> def wrap(f):
> def wrapper(*args, **kw):
> d = f(*args, **kw)
> if isinstance(d, defer.Deferred):
> return d.addCallbacks(callback, errback,
> callbackArgs=args,
> callbackKeywords=kw, errbackArgs=args, errbackKeywords=kw)
> # We were used to decorate a non-inlineCallbacks function.
> raise Exception(
> 'Function %r was decorated with
> inlineCallbacksDecorator but '
> 'did not return a deferred (did you forget
> to also decorate '
> 'with inlineCallbacks?)' % f.__name__)
> return mergeFunctionMetadata(f, wrapper)
> return wrap
>
> You can use it like this:
>
> def _cbok(result, a, b=None):
> print 'In _cbok: a=%r b=%r' % (a, b)
> return result
>
> def _cberr(failure, *args, **kw):
> pass
> # Do something.... and maybe also return the failure.
>
> @inlineCallbacksDecorator(_cbok, _cberr)
> @defer.inlineCallbacks
> def frog(a, b=None):
> print 'a = %r, b = %r' % (a, b)
> result = yield produceDeferred()
> # yield produceErr()
> defer.returnValue(a)
As far as I can see, this decorator could be applied to any function that
returns a Deferred, not just to inlineCallbacks.
Bye,
Maarten
More information about the Twisted-Python
mailing list