跳转到主要内容

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 (6.9 kB 查看哈希值)

上传时间

支持者