Inline Hooks

Inline hooks are defined inline with business logic code. They are manually triggered with user defined arguments which are received by callback functions

Usage

Inline

from pytapable import Hook

# 1. Create our hook
my_hook = Hook()

# 2. Define a function to execute when hook triggers
def my_callback(context, fn_args, fn_kwargs):
   print(f"Hook says: {fn_kwargs['greeting']}")

# 3. Tap into our hook
my_hook.tap('My Tap Name', my_callback)

# 4. Trigger our hook
my_hook.call(greeting="Hi Callback")

>>> "Hook says: Hi Callback"

In a Class

from pytapable import HookableMixin, create_hook_name

# 1. Class extends `HookableMixin`
class Car(HookableMixin):
   HOOK_ON_MOVE = create_hook_name('on_move')

   def __init__(self):
      super(Car, self).__init__()

      # 2. Define the hook
      self.hooks.add_hook(Hook(HOOK_ON_MOVE))

   def move(self, speed=10):
      # 3. Trigger the hook
      self.hooks[HOOK_ON_MOVE].call(speed=speed)
      return f"Moving at {speed}Mph"

Note

When using inline hooks in a class, its useful to have the class extend the HookableMixin class and create the hooks in the self.hooks dictionary. This allows for other classes to inherit hooks.

Inline Hooks Documentation

Hook

class pytapable.Hook(name=None, interceptor=None)[source]
call(**kwargs)[source]

Triggers the hook which executes all the taps with a arguments passed in args, kwargs and a context dict

Note

Only named args are supported

 # Arguments to a callback

"fn_kwargs": **kwargs

context = {
  'hook': Hook,
  'tap': Tap,
}
tap(name, fn)[source]

Creates a Tap for this hook

Parameters
  • name (basestring) – name of the tapable

  • fn (Callable) – callable to execute when hook is triggered

HookableMixin

class pytapable.HookableMixin(*args, **kwargs)[source]

Mixin which instantiates all the decorated class methods. This is needed for decorated class methods

Instantiates an instance property self.hook which is a HookMapping