Python 3.6+中的简单、原始、天真和乐观的钩子
项目描述
自v5.0.0以来,钩子操作采用最小侵入性,无需元类和类装饰器。
状态
版本v3.10.1的状态是Beta。
版本v5.x的状态是Pre-Alpha。
我在生产工作中使用v3.10.1(https://pypi.ac.cn/project/hookery/3.10.1/)。
本文件是为v5.x准备的,目前尚未准备好用于生产。
安装
pip install hookery==3.10.1
基本用法
from hookery import Hook, hooks
class Profile:
on_activated = Hook()
@on_activated
def log_activation(self):
print(f"Activating {self}")
def activate(self):
hooks.trigger(self.on_activated)
class WarehouseProfile(Profile):
@Profile.on_activated
def log_activation(self):
print(f"Warehouse profile {self} is being activated")
@Profile.on_activated
def another_handler(self):
print(f"This will also be printed")
上面的示例演示了以下内容
钩子注册不需要元类、基类或类装饰器。
您可以在同一类中为每个钩子注册任意数量的处理器。
在子类中名为log_activation的处理器不会覆盖父类中同名处理器。
>>> profile = WarehouseProfile()
>>> profile.activate()
Activating <__main__.WarehouseProfile object at 0x103ee66d8>
Warehouse profile <__main__.WarehouseProfile object at 0x103ee66d8> is being activated
This will also be printed
限制
对我们来说,钩子和钩子处理器是类规范的一部分。这意味着一旦类被创建,就不能添加新的钩子或注册新的钩子处理器。如果您想添加功能,您必须修改类或扩展它。
不能将classmethod和staticmethod注册为处理器,因为钩子适用于类的实例,而不是类本身。
最好不要在处理器上添加其他装饰器。
项目详情
关闭
hookery-5.0.1.tar.gz的哈希值
算法 | 哈希摘要 | |
---|---|---|
SHA256 | 1662f054e8939019f72de297e06168b901914e99469f768c6e04a582e07e9ad4 |
|
MD5 | d2e27a135f92687bf046f79e84cff529 |
|
BLAKE2b-256 | 29562bfeb60342c9ea4bf0e6ca498b927b873091f395f4dbe96371b3a4837c3e |