翻译:https://www.bitecode.dev/p/xmas-decorations-part-3
下面介绍了三种装饰器的真实应用场景。
在函数执行前对函数进行检查。标准库的functools.cache
实现了函数缓存的功能。在函数第一次执行时,会正常执行。在函数使用相同参数执行第二次时,检测到函数已经执行过,会跳过执行函数,直接返回缓存值。
from functools import cache
@cache
def expensive_function(a, b):
print("The expensive function runs")
return a + b
expensive_function(1, 2) # 第一次运行
expensive_function(1, 2) # 相同参数第二次,函数不会执行
运行结果,函数只执行了一次:
The expensive function runs
这种思路在许多流行的框架经常出现:
from django.contrib.auth.decorators import login_required
@login_required
def my_view(request): ...
# https://docs.djangoproject.com/en/5.0/topics/auth/default/#the-login-required-decorator
import time
import functools
def basic_throttle(calls_per_second):
def decorator(func):
last_called = 0.0
count = 0
@functools.wraps(func)
def wrapper(*args, **kwargs):
nonlocal last_called, count
current_time = time.time()
# Reset counter if new second
if current_time - last_called >= 1:
last_called = current_time
count = 0
# Enforce the limit
if count < calls_per_second:
count += 1
return func(*args, **kwargs)
return None
return wrapper
return decorator
>>> @basic_throttle(5)
... def send_alert():
... print(f"Alert !")
...
... for i in range(10):
... send_alert()
... time.sleep(0.1)
...
Alert !
Alert !
Alert !
Alert !
Alert !
存储函数的引用以便在后面使用。通常用于事件系统、模式匹配、路由等。
@app.route('/')
def index():
return 'Index Page'
@app.route('/hello')
def hello():
return 'Hello, World'
import pytest
class Fruit:
def __init__(self, name):
self.name = name
def __eq__(self, other):
return self.name == other.name
@pytest.fixture
def my_fruit():
return Fruit("apple")
@pytest.fixture
def fruit_basket(my_fruit):
return [Fruit("banana"), my_fruit]
def test_my_fruit_in_basket(my_fruit, fruit_basket):
assert my_fruit in fruit_basket
我们希望让函数更强大一些,比如显示函数执行时间。
@hosts('user1@host1', 'host2', 'user2@host3')
def my_func():
pass