Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to decorate a function in class #59

Open
johnnysluckydays opened this issue Aug 6, 2019 · 1 comment
Open

How to decorate a function in class #59

johnnysluckydays opened this issue Aug 6, 2019 · 1 comment

Comments

@johnnysluckydays
Copy link

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
Copy link

jpeyret commented Aug 24, 2019

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'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants