A better way to timeout a class method?

Nick Craig-Wood nick at craig-wood.com
Mon Mar 9 19:30:03 EDT 2009


John O'Hagan <research at johnohagan.com> wrote:
>  Is there a concise Pythonic way to write a method with a timeout?
> 
>  I did this:
> 
>  class Eg(object):
> 
>      def get_value(self, timeout):
> 
>          from threading  import Timer
>          self.flag = True
> 
>          def flag_off():
>              self.flag = False
>          timer = Timer(timeout, flag_off)
>          timer.start()
> 
>          while self.flag:
>              #do stuff for a long time to get some value
>              if condition:  #if we ever get the value
>                  self.value = value
>                  break
> 
>  but it seems hackish to have a special "flag" attribute just to manage the 
>  timeout within the the method.

How about something like this

from threading import Timer
        
class Duration(object):
    def __init__(self, duration):
        self.running = True
        self.timer = Timer(duration, self.set_finished)
        self.timer.setDaemon(True)
        self.timer.start()
    def set_finished(self):
        self.running = False
    def __nonzero__(self):
        return self.running

from time import sleep

def long_function():
    duration = Duration(5)
    i = 0
    print "starting"
    while duration:
        print i
        i += 1
        sleep(1)
    print "finished"

long_function()

Which prints

starting
0
1
2
3
4
finished

-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list