3 from __future__ import with_statement
14 _moduleLogger = logging.getLogger("go_utils")
19 Decorator that makes a generator-function into a function that will continue execution on next call
23 @functools.wraps(func)
24 def decorated_func(*args, **kwds):
26 a.append(func(*args, **kwds))
39 Make a function mainloop friendly. the function will be called at the
40 next mainloop idle state.
43 >>> misc.validate_decorator(async)
46 @functools.wraps(func)
47 def new_function(*args, **kwargs):
53 gobject.idle_add(async_function)
60 def __init__(self, func, once = True):
66 assert self.__idleId is None
68 self.__idleId = gobject.idle_add(self._on_once)
70 self.__idleId = gobject.idle_add(self.__func)
73 if self.__idleId is not None:
74 gobject.source_remove(self.__idleId)
77 @misc.log_exception(_moduleLogger)
86 class Timeout(object):
88 def __init__(self, func):
90 self.__timeoutId = None
92 def start(self, **kwds):
93 assert self.__timeoutId is None
96 timeoutInSeconds = kwds["seconds"]
97 assert 0 <= timeoutInSeconds
98 if timeoutInSeconds == 0:
99 self.__timeoutId = gobject.idle_add(self._on_once)
101 timeout_add_seconds(timeoutInSeconds, self._on_once)
104 if self.__timeoutId is not None:
105 gobject.source_remove(self.__timeoutId)
106 self.__timeoutId = None
108 @misc.log_exception(_moduleLogger)
117 def throttled(minDelay, queue):
119 Throttle the calls to a function by queueing all the calls that happen
120 before the minimum delay
124 >>> misc.validate_decorator(throttled(0, Queue.Queue()))
127 def actual_decorator(func):
129 lastCallTime = [None]
133 func, args, kwargs = queue.pop(0)
134 lastCallTime[0] = time.time() * 1000
135 func(*args, **kwargs)
138 @functools.wraps(func)
139 def new_function(*args, **kwargs):
140 now = time.time() * 1000
142 lastCallTime[0] is None or
143 (now - lastCallTime >= minDelay)
145 lastCallTime[0] = now
146 func(*args, **kwargs)
148 queue.append((func, args, kwargs))
149 lastCallDelta = now - lastCallTime[0]
150 processQueueTimeout = int(minDelay * len(queue) - lastCallDelta)
151 gobject.timeout_add(processQueueTimeout, process_queue)
155 return actual_decorator
158 def _old_timeout_add_seconds(timeout, callback):
159 return gobject.timeout_add(timeout * 1000, callback)
162 def _timeout_add_seconds(timeout, callback):
163 return gobject.timeout_add_seconds(timeout, callback)
167 gobject.timeout_add_seconds
168 timeout_add_seconds = _timeout_add_seconds
169 except AttributeError:
170 timeout_add_seconds = _old_timeout_add_seconds