coma.hooks

Hook utilities, factories, and defaults.

Module Attributes

General hook utilities.

hook(fn: Callable[[...], coma.hooks.utils._T]) Callable[[...], coma.hooks.utils._T][source]

Decorator for coma hooks.

Enables hook definitions with only a subset of all protocol parameters.

Example:

@hook
def parser_hook(parser):  # "parser" is a subset of the parser hook protocol
    ...
Parameters

fn (Callable) – Any function that implements a subset of a hook protocol

Returns

A wrapped version of the function that is protocol-friendly

sequence(hook_: Callable, *hooks: Callable, return_all: bool = False) Callable[source]

Wraps a sequence of hooks into a single function.

Equivalent to calling all given hooks one at a time in sequence while passing them all the same parameters. The hooks, therefore, need to have compatible call signatures. The best way to achieve this is to decorate each hook with the @hook decorator and ensuring all hooks subset the same hook protocol.

Example

Replace:

@coma.hooks.hook
def wrapper(parser):
    coma.hooks.parser_hook.factory("-a", default=123)(parser=parser)
    coma.hooks.parser_hook.factory("-b", default=456)(parser=parser)

coma.register(..., parser_hook=wrapper)

with:

wrapper = coma.hooks.sequence(
    coma.hooks.parser_hook.factory("-a", default=123),
    coma.hooks.parser_hook.factory("-b", default=456),
)

coma.register(..., parser_hook=wrapper)
Parameters
  • hook (Callable) – The first hook in the sequence

  • *hooks (Callable) – The remaining hooks in the sequence

  • return_all (bool) – Whether to return all values or the last

Returns

If return_all is False, the wrapper returns the value of the last hook. If return_all is True, the wrapper returns the value of all hooks in a list.

See also