【问题标题】:timeout decorator in python through __init__ paramspython中的超时装饰器通过__init__参数
【发布时间】:2017-01-04 18:57:31
【问题描述】:

我想在 python 中为一个函数(rest API 调用)设置一个超时时间,为此我正在关注this SO 答案。

我已经有一个现有的代码结构,我想要一个超时装饰器。我在“.txt”文件中定义超时秒数并将其作为字典传递给主函数。类似的东西:

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

我错过了什么?

【问题讨论】:

    标签: python python-2.7 function timeout settimeout


    【解决方案1】:

    Aself 没有定义,因为装饰器在方法之外,而 self 只存在于方法内部:

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

    您可以尝试在__init__处设置barTimeout属性:

    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)
    

    【讨论】:

    • 我已经在方法中有一些代码..所以只传递“pass”并不能解决问题
    • @Dave:我认为你错过了答案的重点。不能在方法的装饰器中使用self,因为装饰器在方法之外,而self 只存在于方法内部。
    猜你喜欢
    • 2011-06-30
    • 2016-05-31
    • 2020-04-13
    • 2015-07-14
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 2012-11-01
    • 2014-07-21
    相关资源
    最近更新 更多