Call function in reactor greenlet and block current greenlet waiting for the result

def blockingCallFromGreenlet(*args, **kwargs):
    """Call function in reactor greenlet and block current greenlet waiting for the result"""
    reactor = args[0]
    assert reactor.greenlet != getcurrent(), "can't invoke this in the reactor greenlet"
    func = args[1]
    result = AsyncResult()

    def task():
        try:
            result.set(func(*args[2:], **kwargs))
        except Exception, ex:
            result.set_exception(ex)

    reactor.callFromGreenlet(task)
    value = result.get()
    if isinstance(value, defer.Deferred):
        return waitForDeferred(value)
    else:
        return value