Skip to content

Question about creating plugin instances from setuptools entrypoints #643

@15r10nk

Description

@15r10nk

Hi, I'm in the process of adding a pluggy based plugin system to inline-snapshot and would like to know if I'm on the right path.

Problem:

I want that plugins can define entrypoints in the pyproject.toml like:

[project.entry-points.inline_snapshot]
my_plugin="inline_snapshot_example.plugin:MyPlugin"

and that plugins take a self argument to allow them to store some internal state.

from inline_snapshot.plugin import hookimpl

class MyPlugin:
    @hookimpl
    def customize(self,value,builder):
        # not important for this issue ...
        if isinstance(value,int):
            return builder.create_code("+".join("1"*value))

The problem is that load_setuptools_entrypoints registers only the Plugin class. I copied the code and changed it to instantiate the class when it is a type, which currently solves my use case.

# I copied this function from pluggy
def load_setuptools_entrypoints(self:PluginManager, group: str, name: str | None = None) -> int:
        import importlib.metadata

        count = 0
        for dist in list(importlib.metadata.distributions()):
            for ep in dist.entry_points:
                if (
                    ep.group != group
                    or (name is not None and ep.name != name)
                    # already registered
                    or self.get_plugin(ep.name)
                    or self.is_blocked(ep.name)
                ):
                    continue
                plugin = ep.load()

                # call types to provide the plugin author an instance where he can store some data
                if isinstance(plugin,type):
                    plugin=plugin()

                self.register(plugin, name=ep.name)
                self._plugin_distinfo.append((plugin, DistFacade(dist)))
                count += 1
        return count

I also use a seperate PluginManager instance beside the pytest one because unittest support is also on the roadmap and pytest enforces that hooks start with pytest_.

My Question:

  • This does not look to me like the way it is usually done, am I doing something wrong here?
  • Is there another recommended approach?
  • This issue plans to deprecate load_setuptools_entrypoints, maybe I'm trying to use a function which is already outdated.

Also thank you to everyone who is maintaining pluggy. This is a really useful library.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions