You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/blog/python-decorators-for-beginners.md
+24-9Lines changed: 24 additions & 9 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -3,7 +3,7 @@ title: 'Python Decorators - Simple Patterns to Level Up Your Code - Python Cheat
3
3
description: Decorators are one of Python's most elegant features, allowing you to modify the behavior of functions or methods in a clean and readable way.
4
4
date: Aug 16, 2025
5
5
updated: Aug 16, 2025
6
-
tags: python, intermediate, beta
6
+
tags: python, intermediate, decorators
7
7
socialImage: /blog/python-decorators.jpg
8
8
---
9
9
@@ -192,7 +192,6 @@ def retry(max_attempts=3):
192
192
if attempt == max_attempts -1:
193
193
print("All attempts failed!")
194
194
raise
195
-
returnNone
196
195
return wrapper
197
196
return decorator
198
197
@@ -213,31 +212,47 @@ Sometimes you need to be gentle with APIs or databases:
213
212
214
213
```python
215
214
import time
215
+
import functools
216
216
217
217
def rate_limit(seconds):
218
+
"""
219
+
A decorator to limit how frequently a function can be called.
220
+
"""
218
221
def decorator(func):
219
-
last_called = [^0] # Use list to store mutable value
222
+
# Use a list to store a mutable float value for the last call time.
223
+
# This allows the inner wrapper function to modify it.
224
+
last_called_at = [0.0]
220
225
221
226
@functools.wraps(func)
222
227
def wrapper(*args, **kwargs):
223
-
elapsed = time.time() - last_called
224
-
if elapsed < seconds:
225
-
time.sleep(seconds - elapsed)
228
+
# Calculate time elapsed since the last call
229
+
elapsed = time.time() - last_called_at[0]
230
+
wait_time = seconds - elapsed
231
+
232
+
# If not enough time has passed, sleep for the remainder
233
+
if wait_time >0:
234
+
time.sleep(wait_time)
226
235
227
-
last_called = time.time()
236
+
# Update the last call time and execute the function
237
+
last_called_at[0] = time.time()
228
238
return func(*args, **kwargs)
229
239
230
240
return wrapper
231
241
return decorator
232
242
233
-
@rate_limit(1) #At most once per second
243
+
@rate_limit(1) #Allow at most one call per second
234
244
def call_api():
235
245
print(f"API called at {time.time():.2f}")
236
246
237
-
# These will be spaced out by 1 second each
247
+
# These calls will be spaced out by approximately 1 second each
0 commit comments