The hook() decorator accepts two parameters: object, and method. The object parameter specifies the object in which defines the method to be hooked. The method parameter specifies the method to be hooked. The decorated function, the actual hook, must specify the same operation signature as the original method invocation.
For instance, lets say we want to hook the Package.get_name() method. We would define the hook as follows.
#ECP hook demonstration
from enomalism2.model import Package, hook
@hook(Package, Package.get_name)
def hook_get_name(fn, self):
"""Hook into the Package.get_name() method."""
return 'My Package'
Hooks can also be modeled as event subscriptions, where in the system, each method invocation can be considered a published event. Each defined hook can be considered an event subscription. For example, lets modify the previous example to simulate a pre and post event situation.
#ECP hook pre/post event demonstration
import logging
from enomalism2.model import Package, hook
@hook(Package, Package.get_name)
def hook_get_name(fn, self):
"""Hook into the Package.get_name() method."""
logging.info("Attempting to get the package name...")
result=fn(self)
logging.info("Success.")
return result