def timeout(reactor, deferred, timeout_sec, reason=None):
 def _timeout():
  deferred.cancel()
 delayed_timeout = reactor.callLater(timeout_sec, _timeout)
 if (reason is not None):
  def maybe_replace_reason(passthrough):
   if delayed_timeout.active():
    return passthrough
   return Failure(reason)
  deferred.addErrback(maybe_replace_reason)
 def abort_timeout(passthrough):
  if delayed_timeout.active():
   delayed_timeout.cancel()
  return passthrough
 deferred.addBoth(abort_timeout)
 return deferred

def timeout ( reactor , deferred , timeout_sec , reason = None ) : def _timeout ( ) : deferred . cancel ( ) delayed_timeout = reactor . callLater ( timeout_sec , _timeout ) if ( reason is not None ) : def maybe_replace_reason ( passthrough ) : if delayed_timeout . active ( ) : return passthrough return Failure ( reason ) deferred . addErrback ( maybe_replace_reason ) def abort_timeout ( passthrough ) : if delayed_timeout . active ( ) : delayed_timeout . cancel ( ) return passthrough deferred . addBoth ( abort_timeout ) return deferred
adds a timeout to an existing deferred .