Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

feat: Support sub-extensions with custom hooks #315

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

pawamoy
Copy link
Member

@pawamoy pawamoy commented Aug 19, 2024

This PR would allow users to define custom events, for their own downstream users to implement the corresponding hooks. It's an extension system in the extension system. Inspired by mkdocs/mkdocs#3806.

from ast import AST
from typing import Any

import griffe


##############################################
# Extension writer.
class CustomEvents(griffe.SubExtension):
    # By default, the namespace is the class name.
    namespace = "my_sub_extension"

    def on_whatever(self, param1: str, **kwargs) -> None:
        ...


class SomeExtension(griffe.Extension):
    def on_node(self, agent: griffe.Visitor | griffe.Inspector, **kwargs: Any) -> None:
        # Fire the event, calling hooks declared by downstream users.
        agent.extensions.subcall(CustomEvents.namespace, "on_whatever", param1="Hello!", extra="friends")


##############################################
# User hooks.
class MyHooks(CustomEvents):
    def on_whatever(self, param1: str, **kwargs) -> None:
        print(param1, kwargs)


class SomeRelatedExtension(griffe.Extension):
    sub_extensions = (MyHooks(),)

    # Or declare them in `__init__`, allowing further customization through options.
    def __init__(self, **options) -> None:
        self.sub_extensions = (MyHooks(**options),)


##############################################
# Final user.
extensions = griffe.load_extensions(SomeExtension, SomeRelatedExtension)
...

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant