en un clic
apply-decorator-wrap
// For cross-cutting concerns: add behavior without modifying functions, caching, timing, logging, validation wrappers.
// For cross-cutting concerns: add behavior without modifying functions, caching, timing, logging, validation wrappers.
| name | apply-decorator-wrap |
| description | For cross-cutting concerns: add behavior without modifying functions, caching, timing, logging, validation wrappers. |
Decorators wrap functions to add behavior before, after, or around the original.
def timing(func):
"""Decorator to time function execution."""
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
elapsed = time.time() - start
print(f"{func.__name__} took {elapsed:.3f}s")
return result
return wrapper
@timing
def slow_function():
time.sleep(1)
return "done"
# Equivalent to: slow_function = timing(slow_function)
# Memoization decorator (ngrams.py)
def memo(f):
"""Memoize function f."""
table = {}
def fmemo(*args):
if args not in table:
table[args] = f(*args)
return table[args]
fmemo.memo = table # Expose cache
return fmemo
@memo
def segment(text):
"""Optimal word segmentation."""
if not text:
return []
candidates = ([first] + segment(rest)
for first, rest in splits(text))
return max(candidates, key=word_prob)
# Using functools for cleaner decorators
from functools import cache, lru_cache, wraps
@cache # Built-in memoization
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n-1) + fibonacci(n-2)
@lru_cache(maxsize=1000) # Limited cache size
def expensive_lookup(key):
...
# Reusable decorator with parameter
cache = lru_cache(None) # Alias for unlimited cache
@cache
def expressions(numbers):
...
@cache
def segment(text):
...
@functools.wraps@lru_cache(n) returns decoratorConducts iterative deep research on any topic using web search, progressive exploration, and structured synthesis. Use when asked for comprehensive research, deep investigation, thorough analysis, or multi-source exploration of any topic. Triggers: research, investigate, deep dive, comprehensive analysis, explore thoroughly, find everything about.
For performance work: measure before changing, profile to find bottlenecks, compare before and after.
For symbolic computation: ASTs, mathematical expressions, code that manipulates code structure, expression transformations.
For ordered processing: A* search, Dijkstra, event simulation, task scheduling. Efficient min/max extraction with heap-based queue.
For dynamic programming: overlapping subproblems, recursive solutions with repeated computations, memoization to avoid redundant work.
For persistent state: closures capture outer variables, alternative to classes for simple state, factory functions that remember context.