Conditions | 14 |
Total Lines | 52 |
Lines | 0 |
Ratio | 0 % |
Changes | 1 | ||
Bugs | 0 | Features | 0 |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
Complex classes like rate_limited() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
1 | ''' |
||
125 | def rate_limited(max_per_second, mode='wait', delay_first_call=False): |
||
126 | """ |
||
127 | Decorator that make functions not be called faster than |
||
128 | |||
129 | set mode to 'kill' to just ignore requests that are faster than the |
||
130 | rate. |
||
131 | |||
132 | set mode to 'refresh_timer' to reset the timer on successive calls |
||
133 | |||
134 | set delay_first_call to True to delay the first call as well |
||
135 | """ |
||
136 | lock = threading.Lock() |
||
137 | min_interval = 1.0 / float(max_per_second) |
||
138 | def decorate(func): |
||
139 | last_time_called = [0.0] |
||
140 | @wraps(func) |
||
141 | def rate_limited_function(*args, **kwargs): |
||
142 | def run_func(): |
||
143 | lock.release() |
||
144 | ret = func(*args, **kwargs) |
||
145 | last_time_called[0] = time.perf_counter() |
||
146 | return ret |
||
147 | lock.acquire() |
||
148 | elapsed = time.perf_counter() - last_time_called[0] |
||
149 | left_to_wait = min_interval - elapsed |
||
150 | if delay_first_call: |
||
151 | if left_to_wait > 0: |
||
152 | if mode == 'wait': |
||
153 | time.sleep(left_to_wait) |
||
154 | return run_func() |
||
155 | elif mode == 'kill': |
||
156 | lock.release() |
||
157 | return |
||
158 | else: |
||
159 | return run_func() |
||
160 | else: |
||
161 | if not last_time_called[0] or elapsed > min_interval: |
||
162 | return run_func() |
||
163 | elif mode == 'refresh_timer': |
||
164 | print('Ref timer') |
||
165 | lock.release() |
||
166 | last_time_called[0] += time.perf_counter() |
||
167 | return |
||
168 | elif left_to_wait > 0: |
||
169 | if mode == 'wait': |
||
170 | time.sleep(left_to_wait) |
||
171 | return run_func() |
||
172 | elif mode == 'kill': |
||
173 | lock.release() |
||
174 | return |
||
175 | return rate_limited_function |
||
176 | return decorate |
||
177 | |||
178 |