pnpnpn / timeout-decorator

Timeout decorator for Python
MIT License
628 stars 94 forks source link

How to decorate a function in class #59

Open johnnysluckydays opened 5 years ago

johnnysluckydays commented 5 years ago

I have a class like: class A(object): def init(self): self.timeout=4 @timeout_decorator(self.timeout) # it dosn't work def doanything(self): print("do")

So, how to decorate doanything function in A class? Thanks

jpeyret commented 5 years ago

why would it work? your function doesn't take any time.

This worked for me (I am trying to time-limit unittest.assertEqual so I wanted to decorate it ):

from timeout_decorator import timeout, TimeoutError as CustomTimeoutError
from time import time, sleep

class TimeItOut:

    def __init__(self, wait_=1, maxtime=.2):

        self.wait_= wait_

    # @timeout(.2)  this should work for what you want, I am testing 
    # how to decorate an existing function
    def process(self):
        start = time()
        sleep(self.wait_)
        print("process.duration:%s" % (time()-start))        
        return self

    @timeout(.2)
    def timedprocess(self):
        self.process()
        return self

try:
    TimeItOut(.1).process().timedprocess()
    TimeItOut(.3).process().timedprocess()
except (CustomTimeoutError,) as e: #pragma: no cover
    print("caught you:%s" % (e))

output:

process.duration:0.1050870418548584
process.duration:0.10171890258789062
process.duration:0.30275774002075195
caught you:'Timed Out'