timeout decorator in python through __init__ params
<p>I want to have a timeout for a function (rest API call) in python &amp; for that I am following <a href="http://stackoverflow.com/a/2282656/5582349">this</a> SO answer.    </p>

<p>I already have one existing code structure where i want to have a timeout decorator. I am defining a timeout seconds in ".txt" file &amp; passing it as a dict to main function. Something like :   </p>

<pre><code>class Foo():
    def __init__(self, params):
        self.timeout=params.get['timeout']
        ....
        ....

    @timeout(self.timeout)    #throws an error
    def bar(arg1,arg2,arg3,argn):
        pass
        #handle timeout for this function by getting timeout from __init__
        #As answer given in SO , 
        #I need to use the self.timeout, which is throwing an error:
        ***signal.alarm(seconds)
        TypeError: an integer is required*** 
        #And also 
        ***@timeout(self.timeout)
        NameError: name 'self' is not defined***

   @timeout(30)    #Works fine without any issue
    def foo_bar(arg1,arg2,arg3,argn):
         pass
</code></pre>

<p>What am i missing ? </p>

<p>At <code>A</code> the <code>self</code> is not defined because the decorator is outside the method, but self only exists inside the method:</p>

<pre><code>@timeout(self.timeout)    # &lt;== A
def bar(self,arg1,arg2,arg3):
    pass
</code></pre>

<p>You can try to set the <code>barTimeout</code> attribute at <code>__init__</code>:</p>

<pre><code>class Foo():

    def bar(self,arg1,arg2,arg3):
        pass

    def __init__(self, params):
        self.timeout=params.get('timeout')
        self.barTimeout = timeout(self.timeout)(self.bar)

Foo({'timeout':30}).barTimeout(1,2,3)
</code></pre>

python python-2.7 function timeout settimeout