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¶
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. IfNone
, the defaultself.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.
- 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 forhook("contexthook", name)
.