def maybeDeferred(f, *args, **kw):
    """
    Copied from twsited.internet.defer and add a check to detect fibers.
    """
    try:
        result = f(*args, **kw)
    except Exception:
        return fail(failure.Failure())

    if IFiber.providedBy(result):
        import traceback
        frames = traceback.extract_stack()
        msg = "%s returned a fiber instead of a deferred" % (f, )
        if len(frames) > 1:
            msg += "; called from %s" % (frames[-2], )
        raise RuntimeError(msg)

    if isinstance(result, Deferred):
        return result
    elif isinstance(result, failure.Failure):
        return fail(result)
    else:
        return succeed(result)