function guard_execution
A decorator factory that prevents rapid repeated execution of a function by enforcing a cooldown period between calls.
/tf/active/vicechatdev/CDocs/__init__.py
103 - 124
moderate
Purpose
This decorator is designed to throttle function execution by implementing a guard mechanism with a configurable cooldown period. It prevents a decorated function from being called multiple times within the specified cooldown window (in milliseconds). If a function is called while still in cooldown, it returns None instead of executing. This is useful for rate-limiting, preventing duplicate operations, debouncing user actions, or protecting against rapid-fire function calls that could cause performance issues or unintended side effects.
Source Code
def guard_execution(cooldown_ms=500):
"""Decorator to prevent repeated function calls."""
def decorator(func):
import functools
@functools.wraps(func)
def wrapper(*args, **kwargs):
func_name = f"{func.__module__}.{func.__name__}"
# Check if we should execute
if not execution_guard.guard(func_name, cooldown_ms):
return None
try:
# Execute the function
return func(*args, **kwargs)
finally:
# Release the guard
execution_guard.release(func_name)
return wrapper
return decorator
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
cooldown_ms |
- | 500 | positional_or_keyword |
Parameter Details
cooldown_ms: The cooldown period in milliseconds (default: 500). This defines the minimum time that must elapse between successful executions of the decorated function. If the function is called again before this period expires, the call is blocked and None is returned. Must be a positive integer or float representing milliseconds.
Return Value
Returns a decorator function that wraps the target function. When the decorated function is called: (1) If the cooldown period has elapsed or this is the first call, it executes the function and returns its original return value. (2) If called during the cooldown period, it returns None without executing the function. The actual return type depends on the wrapped function's return type, or None if execution is blocked.
Dependencies
functools
Required Imports
import functools
Conditional/Optional Imports
These imports are only needed under specific conditions:
import functools
Condition: imported lazily inside the decorator function, always needed when decorator is applied
Required (conditional)Usage Example
# Assuming execution_guard is properly initialized
# Example 1: Basic usage with default cooldown
@guard_execution()
def process_data():
print("Processing data...")
return "Data processed"
result1 = process_data() # Executes normally, returns "Data processed"
result2 = process_data() # Called immediately, returns None (blocked by cooldown)
# Example 2: Custom cooldown period
@guard_execution(cooldown_ms=1000)
def save_file(filename):
print(f"Saving {filename}...")
with open(filename, 'w') as f:
f.write("data")
return True
result = save_file('test.txt') # Executes and returns True
import time
time.sleep(0.5)
result = save_file('test.txt') # Returns None (still in cooldown)
time.sleep(0.6)
result = save_file('test.txt') # Executes and returns True (cooldown expired)
Best Practices
- Ensure the 'execution_guard' object is properly initialized and available in the global scope before using this decorator
- Be aware that blocked calls return None - handle this in calling code to avoid NoneType errors
- The cooldown is tracked per function using its fully qualified name (module.function_name), so functions with the same name in different modules are tracked separately
- The decorator uses a try-finally block to ensure the guard is always released, even if the function raises an exception
- Choose an appropriate cooldown_ms value based on your use case - too short may not prevent rapid calls effectively, too long may impact user experience
- This decorator is not thread-safe by itself - thread safety depends on the implementation of the execution_guard object
- Consider logging or monitoring when calls are blocked to understand usage patterns and adjust cooldown periods
- The lazy import of functools inside the decorator means the import happens at decoration time, not at module load time
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
class ExecutionGuard 76.7% similar
-
function cache_result 50.5% similar
-
function with_lock 50.0% similar
-
function transaction 45.6% similar
-
function require_auth 45.2% similar