Zope Hookable

8.2 · active · verified Tue Apr 14

Zope Hookable is a Python package that facilitates the efficient creation of "hookable" objects. These are callable objects designed to be optionally replaced at runtime. This allows developers to define a default behavior for a function and then dynamically change its implementation, affecting all users of that function, even those who imported it. The current version is 8.2 and it is part of the Zope ecosystem, which generally follows semantic versioning with minor releases every 2-6 months and major releases every 2-3 years, though `zope.hookable` itself has a less frequent major release cycle.

Warnings

Install

Imports

Quickstart

This example demonstrates how to define a hookable function, dynamically replace its implementation using `sethook`, and then revert to the original default implementation with `reset()`.

from zope.hookable import hookable

# 1. Define a default implementation for a function
def _my_default_function(name):
    return f"Hello, {name} (default) via id {id(_my_default_function)}"

# 2. Make it hookable
my_hookable_function = hookable(_my_default_function)

# 3. Use the hookable function - it calls the default implementation
print(f"Initial call: {my_hookable_function('World')}")

# 4. Define a new implementation
def _my_custom_function(name):
    return f"Greetings, {name} (custom) via id {id(_my_custom_function)}"

# 5. Set the hook to the new implementation
my_hookable_function.sethook(_my_custom_function)

# 6. The function now uses the new implementation
print(f"After hook:   {my_hookable_function('User')}")

# 7. Define another implementation
def _my_another_function(name, greeting='Hi'):
    return f"{greeting}, {name} (another) via id {id(_my_another_function)}"

# 8. Set another hook, passing additional arguments if necessary for the new hook's signature
my_hookable_function.sethook(_my_another_function, 'Hola')

print(f"Another hook: {my_hookable_function('Friend')}")

# 9. Reset to the original default implementation
my_hookable_function.reset()
print(f"After reset:  {my_hookable_function('Again')}")

view raw JSON →