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 | ''' |
||
119 | def rate_limited(max_per_second, mode='wait', delay_first_call=False): |
||
120 | """ |
||
121 | Decorator that make functions not be called faster than |
||
122 | |||
123 | set mode to 'kill' to just ignore requests that are faster than the |
||
124 | rate. |
||
125 | |||
126 | set mode to 'refresh_timer' to reset the timer on successive calls |
||
127 | |||
128 | set delay_first_call to True to delay the first call as well |
||
129 | """ |
||
130 | lock = threading.Lock() |
||
131 | min_interval = 1.0 / float(max_per_second) |
||
132 | def decorate(func): |
||
133 | last_time_called = [0.0] |
||
134 | @wraps(func) |
||
135 | def rate_limited_function(*args, **kwargs): |
||
136 | def run_func(): |
||
137 | lock.release() |
||
138 | ret = func(*args, **kwargs) |
||
139 | last_time_called[0] = time.perf_counter() |
||
140 | return ret |
||
141 | lock.acquire() |
||
142 | elapsed = time.perf_counter() - last_time_called[0] |
||
143 | left_to_wait = min_interval - elapsed |
||
144 | if delay_first_call: |
||
145 | if left_to_wait > 0: |
||
146 | if mode == 'wait': |
||
147 | time.sleep(left_to_wait) |
||
148 | return run_func() |
||
149 | elif mode == 'kill': |
||
150 | lock.release() |
||
151 | return |
||
152 | else: |
||
153 | return run_func() |
||
154 | else: |
||
155 | if not last_time_called[0] or elapsed > min_interval: |
||
156 | return run_func() |
||
157 | elif mode == 'refresh_timer': |
||
158 | print('Ref timer') |
||
159 | lock.release() |
||
160 | last_time_called[0] += time.perf_counter() |
||
161 | return |
||
162 | elif left_to_wait > 0: |
||
163 | if mode == 'wait': |
||
164 | time.sleep(left_to_wait) |
||
165 | return run_func() |
||
166 | elif mode == 'kill': |
||
167 | lock.release() |
||
168 | return |
||
169 | return rate_limited_function |
||
170 | return decorate |
||
171 | |||
172 |