|
| 1 | +--- |
| 2 | +file: creational/lazy_evaluation.py |
| 3 | +chunk: creational_lazy_evaluation.md |
| 4 | +--- |
| 5 | + |
| 6 | +```python |
| 7 | +""" |
| 8 | +lazy_evaluation.py |
| 9 | +
|
| 10 | +Demonstrates the Lazy Evaluation pattern in Python using a custom @lazy_property decorator. |
| 11 | +This pattern is useful when you want to delay the evaluation of a resource-intensive |
| 12 | +property until it is actually accessed. |
| 13 | +
|
| 14 | +""" |
| 15 | + |
| 16 | +import time |
| 17 | +from functools import wraps |
| 18 | + |
| 19 | +def lazy_property(func): |
| 20 | + """ |
| 21 | + A decorator that converts a method into a lazily evaluated property. |
| 22 | + The result is cached after the first computation. |
| 23 | +
|
| 24 | + Usage: |
| 25 | + @lazy_property |
| 26 | + def expensive_computation(self): ... |
| 27 | + """ |
| 28 | + attr_name = f"_lazy_{func.__name__}" |
| 29 | + |
| 30 | + @property |
| 31 | + @wraps(func) |
| 32 | + def wrapper(self): |
| 33 | + if not hasattr(self, attr_name): |
| 34 | + print(f"🔄 Computing '{func.__name__}'...") |
| 35 | + setattr(self, attr_name, func(self)) |
| 36 | + return getattr(self, attr_name) |
| 37 | + |
| 38 | + return wrapper |
| 39 | + |
| 40 | + |
| 41 | +# ============================ |
| 42 | +# Lazy Evaluation Example Class |
| 43 | +# ============================ |
| 44 | + |
| 45 | +class ReportGenerator: |
| 46 | + """ |
| 47 | + Simulates a class that generates an expensive report. |
| 48 | + Lazy evaluation is used so the report is not computed until needed. |
| 49 | + """ |
| 50 | + |
| 51 | + def __init__(self, data: list): |
| 52 | + self.data = data |
| 53 | + |
| 54 | + @lazy_property |
| 55 | + def summary(self): |
| 56 | + """ |
| 57 | + Simulates a time-consuming operation. |
| 58 | + """ |
| 59 | + time.sleep(2) # Simulate heavy computation |
| 60 | + return { |
| 61 | + "total": len(self.data), |
| 62 | + "min": min(self.data), |
| 63 | + "max": max(self.data), |
| 64 | + "average": sum(self.data) / len(self.data) |
| 65 | + } |
| 66 | + |
| 67 | + def show_summary(self): |
| 68 | + """Displays the report summary.""" |
| 69 | + print("📊 Report Summary:") |
| 70 | + for key, value in self.summary.items(): |
| 71 | + print(f" - {key.capitalize()}: {value}") |
| 72 | + |
| 73 | + |
| 74 | +# ============================ |
| 75 | +# Demonstration |
| 76 | +# ============================ |
| 77 | + |
| 78 | +def main(): |
| 79 | + print("🐢 Lazy Evaluation Pattern Demo 🐢\n") |
| 80 | + |
| 81 | + numbers = list(range(1, 1_000_001)) # Large dataset |
| 82 | + report = ReportGenerator(numbers) |
| 83 | + |
| 84 | + print("Step 1: Object created, report not yet generated.") |
| 85 | + time.sleep(1) |
| 86 | + |
| 87 | + print("\nStep 2: Accessing the summary for the first time (will compute)...") |
| 88 | + report.show_summary() |
| 89 | + |
| 90 | + print("\nStep 3: Accessing the summary again (should be cached)...") |
| 91 | + report.show_summary() |
| 92 | + |
| 93 | + |
| 94 | +if __name__ == "__main__": |
| 95 | + main() |
| 96 | + |
| 97 | + |
| 98 | +# 🐢 Lazy Evaluation Pattern Sample Output 🐢 |
| 99 | + |
| 100 | +# Step 1: Object created, report not yet generated. |
| 101 | + |
| 102 | +# Step 2: Accessing the summary for the first time (will compute)... |
| 103 | +# 🔄 Computing 'summary'... |
| 104 | +# 📊 Report Summary: |
| 105 | +# - Total: 1000000 |
| 106 | +# - Min: 1 |
| 107 | +# - Max: 1000000 |
| 108 | +# - Average: 500000.5 |
| 109 | + |
| 110 | +# Step 3: Accessing the summary again (should be cached)... |
| 111 | +# 📊 Report Summary: |
| 112 | +# - Total: 1000000 |
| 113 | +# - Min: 1 |
| 114 | +# - Max: 1000000 |
| 115 | +# - Average: 500000.5 |
| 116 | + |
| 117 | +``` |
| 118 | + |
| 119 | +## Summary |
| 120 | +Demonstrates the Lazy Evaluation pattern in Python using a custom @lazy_property decorator. This pattern delays the evaluation of a resource-intensive property until it is accessed, thus optimizing performance. |
| 121 | + |
| 122 | +## Docstrings |
| 123 | +- A decorator that converts a method into a lazily evaluated property. The result is cached after the first computation. |
| 124 | +- Simulates a time-consuming operation. Delays the computation of the report summary until it is accessed. |
| 125 | +- Displays the report summary. |
| 126 | + |
0 commit comments