evariste.hooks

Implement hook mechanism.

See Hooks for more information.

Note

This implementation of hooks rely on other parts of Évariste (plugins for example), and cannot be used separatedly.

Example

Example of hook mechanism
import contextlib

from evariste import hooks

class A:

    @hooks.setmethodhook()
    def a(self):
        print("Running A.a()…")

class B:

    @hooks.contexthook("A.a"):
    @contextlib.contextmanager
    def b(self):
        print("Before running A.a()…").
        yield
        print("After running A.a()…").

# Let's go!
A.a()

In this example, the A.a() method has been marked as accepting hooks, and the B.b() method has been registered as a hook for A.a().

When A.a() is run (last line of the example), although B has not been called directly, B.b() is called as well, as a registered hook. The output of this example is:

Before running A.a()…
Running A.a()…
After running A.a()…

Get functions registered as hooks

Method hooks

Methods can be marked to accept hooks using the following function.

evariste.hooks.setmethodhook(*, getter: None | Callable = None) Callable[source]

Decorator to mark that a method can accept method and context Hooks.

Parameters:

getter (function) – Function that, given the instance object as argument, returns a plugins.Loader object. If None, the default self.shared.builder.plugins is used (self is supposed to have this attribute).

Context hooks

Context hooks cannot be directly defined: every method hook is also a context hook.

Iteration hooks

Iteration hooks can be executed using applyiterhook().

Register functions as hooks

evariste.hooks.hook(hooktype: str, name: str) Callable[source]

Decorator to register a function or method as a hook.

Parameters:
  • hooktype (str) – Type of hook ("methodhook" or "contexthook", or whatever string you want).

  • name (str) – Name of the target hook, of the form Class.methodname (or Class only for the __init__ method).

evariste.hooks.contexthook(name: str) Callable[source]

Decorator to register a function or method as a context hook.

For any string name, contexthook(name) is a shortcut for hook("contexthook", name).

evariste.hooks.methodhook(name: str) Callable[source]

Decorator to register a function or method as a method hook.

For any string name, methodhook(name) is a shortcut for hook("methodhook", name).

evariste.hooks.iterhook(name: str) Callable[source]

Decorator to register a function or method as an iter hook.

For any string name, iterhook(name) is a shortcut for hook("iterhook", name).