title: How to write a timeout decorator which can get a function or a decorated function?
body: <p>I have the following timeout creation decorator function:</p>
  
  <pre><code>class TimeoutError(Exception): pass
  
  
  def timeout(seconds, error_message = 'Function call timed out'):
      def decorated(func):
          print "timeout: \t" + func.__name__
          def _handle_timeout(signum, frame):
              raise TimeoutError(error_message)
  
  
          def wrapper(*args, **kwargs):
              signal.signal(signal.SIGALRM, _handle_timeout)
              signal.alarm(seconds)
              try:
                  print "timeout wrapper: \t" + func.__name__
                  result = func(*args, **kwargs)
              finally:
                  signal.alarm(0)
              return result
  
          return functools.wraps(func)(wrapper)
  
      return decorated
  </code></pre>
  
  <p>And another decorator:</p>
  
  <pre><code>import inspect
  
  class withHostAndToken(object):
  
      __name__ = "withHostAndToken"
      __doc__ = "Get the Host and Token for the API call"
  
      def __init__(self, func):
          print "withHostAndToken: \t" + func.__name__
          self.func = func
          self.HOST = ''
          self.TOKEN = ''
  
      def __call__(self,*args, **kwds):
  
          if self.HOST == '':
              self.HOST = "HOST"
          if self.TOKEN == '':
              self.TOKEN = "TOKEN"
  
          argsspec = inspect.getargspec(self.func)
          function_args = argsspec[0]
          if 'HOST' in function_args:
              if 'TOKEN' in function_args:
                  return self.func(self.HOST , self.TOKEN , *args, **kwds)
              else:
                  return self.func(self.HOST  , *args, **kwds)
          elif 'TOKEN' in function_args:
              return self.func(self.TOKEN, *args, **kwds)
  </code></pre>
  
  <p>When I try to apply both to a function I don;t get the function code to be called:</p>
  
  <pre><code>@timeout(2)
  @withHostAndToken
  def testDecorators():
      print __name__
      while True:
          print '.'
  
  testDecorators()
  </code></pre>
  
  <blockquote>
    <p>the output of this is:</p>
    
    <p>withHostAndToken:     testDecorators<br>
    timeout:  withHostAndToken<br>
    timeout wrapper:  withHostAndToken</p>
    
    <p>Process finished with exit code 0</p>
  </blockquote>