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)
80 @misc.log_exception(_moduleLogger)
89 class Timeout(object):
91 def __init__(self, func):
93 self.__timeoutId = None
95 def start(self, **kwds):
96 assert self.__timeoutId is None
99 timeoutInSeconds = kwds["seconds"]
100 assert 0 <= timeoutInSeconds
101 if timeoutInSeconds == 0:
102 self.__timeoutId = gobject.idle_add(self._on_once)
104 timeout_add_seconds(timeoutInSeconds, self._on_once)
107 if self.__timeoutId is not None:
108 gobject.source_remove(self.__timeoutId)
109 self.__timeoutId = None
111 def __call__(self, **kwds):
112 return self.start(**kwds)
114 @misc.log_exception(_moduleLogger)
123 def throttled(minDelay, queue):
125 Throttle the calls to a function by queueing all the calls that happen
126 before the minimum delay
130 >>> misc.validate_decorator(throttled(0, Queue.Queue()))
133 def actual_decorator(func):
135 lastCallTime = [None]
139 func, args, kwargs = queue.pop(0)
140 lastCallTime[0] = time.time() * 1000
141 func(*args, **kwargs)
144 @functools.wraps(func)
145 def new_function(*args, **kwargs):
146 now = time.time() * 1000
148 lastCallTime[0] is None or
149 (now - lastCallTime >= minDelay)
151 lastCallTime[0] = now
152 func(*args, **kwargs)
154 queue.append((func, args, kwargs))
155 lastCallDelta = now - lastCallTime[0]
156 processQueueTimeout = int(minDelay * len(queue) - lastCallDelta)
157 gobject.timeout_add(processQueueTimeout, process_queue)
161 return actual_decorator
164 def _old_timeout_add_seconds(timeout, callback):
165 return gobject.timeout_add(timeout * 1000, callback)
168 def _timeout_add_seconds(timeout, callback):
169 return gobject.timeout_add_seconds(timeout, callback)
173 gobject.timeout_add_seconds
174 timeout_add_seconds = _timeout_add_seconds
175 except AttributeError:
176 timeout_add_seconds = _old_timeout_add_seconds