-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy path03_decorators.py
More file actions
421 lines (333 loc) · 11.2 KB
/
03_decorators.py
File metadata and controls
421 lines (333 loc) · 11.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
"""
================================================================================
File: 03_decorators.py
Topic: Decorators in Python
================================================================================
This file demonstrates decorators in Python. Decorators are a powerful feature
that allows you to modify or enhance functions without changing their code.
They use the @ syntax and are widely used for logging, authentication, caching,
and more.
Key Concepts:
- Function as first-class objects
- Simple decorators
- Decorators with arguments
- Preserving function metadata
- Class decorators
- Built-in decorators
================================================================================
"""
# -----------------------------------------------------------------------------
# 1. Functions as First-Class Objects
# -----------------------------------------------------------------------------
# Functions can be assigned, passed, and returned
print("--- Functions as First-Class Objects ---")
def greet(name):
return f"Hello, {name}!"
# Assign to variable
say_hello = greet
print(say_hello("World"))
# Pass as argument
def apply_func(func, value):
return func(value)
print(apply_func(greet, "Python"))
# Return from function
def get_greeter():
def inner_greet(name):
return f"Hi, {name}!"
return inner_greet
greeter = get_greeter()
print(greeter("Alice"))
# -----------------------------------------------------------------------------
# 2. Simple Decorator
# -----------------------------------------------------------------------------
# A decorator wraps a function to add behavior
print("\n--- Simple Decorator ---")
def my_decorator(func):
"""A simple decorator."""
def wrapper(*args, **kwargs):
print(" Before function call")
result = func(*args, **kwargs)
print(" After function call")
return result
return wrapper
# Applying decorator manually
def say_hello_v1(name):
print(f" Hello, {name}!")
decorated = my_decorator(say_hello_v1)
decorated("World")
# Using @ syntax (syntactic sugar)
@my_decorator
def say_hello_v2(name):
print(f" Hello, {name}!")
print("\nWith @ syntax:")
say_hello_v2("Python")
# -----------------------------------------------------------------------------
# 3. Preserving Function Metadata
# -----------------------------------------------------------------------------
# Use functools.wraps to preserve original function info
print("\n--- Preserving Metadata ---")
from functools import wraps
def better_decorator(func):
"""Decorator that preserves function metadata."""
@wraps(func) # Preserve original function's metadata
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
@better_decorator
def example_function():
"""This is the docstring."""
pass
print(f"Function name: {example_function.__name__}")
print(f"Function docstring: {example_function.__doc__}")
# Without @wraps, these would show 'wrapper' info instead
# -----------------------------------------------------------------------------
# 4. Practical Decorators
# -----------------------------------------------------------------------------
print("\n--- Practical Decorators ---")
import time
# Timing decorator
def timer(func):
"""Measure function execution time."""
@wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f" {func.__name__} took {end - start:.4f} seconds")
return result
return wrapper
@timer
def slow_function():
"""A deliberately slow function."""
time.sleep(0.1)
return "Done"
result = slow_function()
# Logging decorator
def logger(func):
"""Log function calls."""
@wraps(func)
def wrapper(*args, **kwargs):
args_str = ", ".join(map(repr, args))
kwargs_str = ", ".join(f"{k}={v!r}" for k, v in kwargs.items())
all_args = ", ".join(filter(None, [args_str, kwargs_str]))
print(f" Calling {func.__name__}({all_args})")
result = func(*args, **kwargs)
print(f" {func.__name__} returned {result!r}")
return result
return wrapper
@logger
def add(a, b):
return a + b
print("\nLogger example:")
add(3, 5)
# -----------------------------------------------------------------------------
# 5. Decorators with Arguments
# -----------------------------------------------------------------------------
# Create configurable decorators with an extra layer
print("\n--- Decorators with Arguments ---")
def repeat(times):
"""Decorator to repeat function calls."""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
results = []
for _ in range(times):
results.append(func(*args, **kwargs))
return results
return wrapper
return decorator
@repeat(times=3)
def greet_user(name):
print(f" Hello, {name}!")
return f"Greeted {name}"
print("Repeat decorator:")
results = greet_user("Alice")
print(f"Results: {results}")
# Retry decorator with custom attempts
def retry(max_attempts=3, exceptions=(Exception,)):
"""Retry function on failure."""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
for attempt in range(1, max_attempts + 1):
try:
return func(*args, **kwargs)
except exceptions as e:
print(f" Attempt {attempt} failed: {e}")
if attempt == max_attempts:
raise
return wrapper
return decorator
attempt_count = 0
@retry(max_attempts=3)
def unstable_function():
global attempt_count
attempt_count += 1
if attempt_count < 3:
raise ValueError("Not ready yet!")
return "Success!"
print("\nRetry decorator:")
try:
result = unstable_function()
print(f" Final result: {result}")
except ValueError:
print(" All attempts failed")
# -----------------------------------------------------------------------------
# 6. Multiple Decorators
# -----------------------------------------------------------------------------
# Decorators stack from bottom to top
print("\n--- Multiple Decorators ---")
def bold(func):
@wraps(func)
def wrapper(*args, **kwargs):
return f"<b>{func(*args, **kwargs)}</b>"
return wrapper
def italic(func):
@wraps(func)
def wrapper(*args, **kwargs):
return f"<i>{func(*args, **kwargs)}</i>"
return wrapper
@bold
@italic
def greet_html(name):
return f"Hello, {name}"
# Applied bottom-up: italic first, then bold
# Same as: bold(italic(greet_html))
print(f"Stacked decorators: {greet_html('World')}")
# -----------------------------------------------------------------------------
# 7. Class-Based Decorators
# -----------------------------------------------------------------------------
# Use a class as a decorator
print("\n--- Class-Based Decorators ---")
class CallCounter:
"""Decorator class to count function calls."""
def __init__(self, func):
self.func = func
self.count = 0
# Preserve function attributes
self.__name__ = func.__name__
self.__doc__ = func.__doc__
def __call__(self, *args, **kwargs):
self.count += 1
print(f" {self.func.__name__} has been called {self.count} time(s)")
return self.func(*args, **kwargs)
@CallCounter
def hello():
"""Say hello."""
print(" Hello!")
hello()
hello()
hello()
print(f"Total calls: {hello.count}")
# -----------------------------------------------------------------------------
# 8. Built-in Decorators
# -----------------------------------------------------------------------------
print("\n--- Built-in Decorators ---")
# @property - create getter/setter
class Circle:
def __init__(self, radius):
self._radius = radius
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, value):
if value < 0:
raise ValueError("Radius cannot be negative")
self._radius = value
@property
def area(self):
import math
return math.pi * self._radius ** 2
circle = Circle(5)
print(f"Circle radius: {circle.radius}")
print(f"Circle area: {circle.area:.2f}")
# @staticmethod - method without self
class Math:
@staticmethod
def add(a, b):
return a + b
print(f"\n@staticmethod: Math.add(3, 4) = {Math.add(3, 4)}")
# @classmethod - method with cls instead of self
class Counter:
count = 0
def __init__(self):
Counter.count += 1
@classmethod
def get_count(cls):
return cls.count
c1, c2, c3 = Counter(), Counter(), Counter()
print(f"@classmethod: Counter.get_count() = {Counter.get_count()}")
# @functools.lru_cache - memoization
from functools import lru_cache
@lru_cache(maxsize=128)
def fibonacci(n):
if n < 2:
return n
return fibonacci(n-1) + fibonacci(n-2)
print(f"\n@lru_cache: fibonacci(30) = {fibonacci(30)}")
print(f"Cache info: {fibonacci.cache_info()}")
# -----------------------------------------------------------------------------
# 9. Decorator for Methods
# -----------------------------------------------------------------------------
print("\n--- Decorating Methods ---")
def debug_method(func):
"""Debug decorator for class methods."""
@wraps(func)
def wrapper(self, *args, **kwargs):
class_name = self.__class__.__name__
print(f" {class_name}.{func.__name__} called")
return func(self, *args, **kwargs)
return wrapper
class Calculator:
@debug_method
def add(self, a, b):
return a + b
@debug_method
def multiply(self, a, b):
return a * b
calc = Calculator()
calc.add(3, 5)
calc.multiply(4, 6)
# -----------------------------------------------------------------------------
# 10. Practical Examples
# -----------------------------------------------------------------------------
print("\n--- Practical Examples ---")
# 1. Authorization decorator
def require_auth(func):
"""Check if user is authenticated."""
@wraps(func)
def wrapper(user, *args, **kwargs):
if not user.get("authenticated", False):
raise PermissionError("Authentication required")
return func(user, *args, **kwargs)
return wrapper
@require_auth
def get_secret_data(user):
return f"Secret data for {user['name']}"
print("Authorization decorator:")
try:
result = get_secret_data({"name": "Guest", "authenticated": False})
except PermissionError as e:
print(f" Denied: {e}")
result = get_secret_data({"name": "Admin", "authenticated": True})
print(f" Allowed: {result}")
# 2. Validation decorator
def validate_positive(func):
"""Ensure all numeric arguments are positive."""
@wraps(func)
def wrapper(*args, **kwargs):
for arg in args:
if isinstance(arg, (int, float)) and arg < 0:
raise ValueError(f"Negative value not allowed: {arg}")
return func(*args, **kwargs)
return wrapper
@validate_positive
def calculate_area(width, height):
return width * height
print("\nValidation decorator:")
try:
calculate_area(-5, 10)
except ValueError as e:
print(f" Validation error: {e}")
print(f" Valid call: {calculate_area(5, 10)}")