2

I want to have a timeout for a function (rest API call) in python & for that I am following this SO answer.

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

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

What am i missing ?

Community
  • 1
  • 1
Dave
  • 221
  • 2
  • 12

1 Answers1

0

At A the self is not defined because the decorator is outside the method, but self only exists inside the method:

@timeout(self.timeout)    # <== A
def bar(self,arg1,arg2,arg3):
    pass

You can try to set the barTimeout attribute at __init__:

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)
napuzba
  • 6,033
  • 3
  • 21
  • 32
  • I already have some code inside the method..So just passing "pass" won't solve the issue – Dave Aug 28 '16 at 18:45
  • 1
    @Dave: I think you're missing the point of the answer. You can't use `self` in a decorator on a method because the decorator is outside the method, but `self` only exists inside the method. – BrenBarn Aug 28 '16 at 19:01