Skip to content

ENH: Support Plugin Accessors Via Entry Points #61499

New issue

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

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

Already on GitHub? Sign in to your account

Open
wants to merge 13 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/source/whatsnew/v3.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ Other enhancements
- Improved deprecation message for offset aliases (:issue:`60820`)
- Multiplying two :class:`DateOffset` objects will now raise a ``TypeError`` instead of a ``RecursionError`` (:issue:`59442`)
- Restore support for reading Stata 104-format and enable reading 103-format dta files (:issue:`58554`)
- Support :class:`DataFrame`, :class:`Series` and :class:`Index` plugin accessors via entry points (:issue:`29076`)
- Support passing a :class:`Iterable[Hashable]` input to :meth:`DataFrame.drop_duplicates` (:issue:`59237`)
- Support reading Stata 102-format (Stata 1) dta files (:issue:`58978`)
- Support reading Stata 110-format (Stata 7) dta files (:issue:`47176`)
Expand Down
5 changes: 5 additions & 0 deletions pandas/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -346,3 +346,8 @@
"unique",
"wide_to_long",
]

from .core.accessor import accessor_entry_point_loader

accessor_entry_point_loader()
del accessor_entry_point_loader
116 changes: 116 additions & 0 deletions pandas/core/accessor.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,11 @@
from pandas import Index
from pandas.core.generic import NDFrame

from importlib.metadata import (
EntryPoints,
entry_points,
)


class DirNamesMixin:
_accessors: set[str] = set()
Expand Down Expand Up @@ -393,3 +398,114 @@ def register_index_accessor(name: str) -> Callable[[TypeT], TypeT]:
from pandas import Index

return _register_accessor(name, Index)


def accessor_entry_point_loader() -> None:
"""
Load and register pandas accessors declared via entry points.

This function scans the 'pandas.<pd_obj>.accessor' entry point group for
accessors registered by third-party packages. Each entry point is expected
to follow the format:

# setup.py
entry_points={
'pandas.DataFrame.accessor': [ <name> = <module>:<AccessorClass>, ... ],
'pandas.Series.accessor': [ <name> = <module>:<AccessorClass>, ... ],
'pandas.Index.accessor': [ <name> = <module>:<AccessorClass>, ... ],
}

OR for pyproject.toml file:

# pyproject.toml
[project.entry-points."pandas.DataFrame.accessor"]
<name> = "<module>:<AccessorClass>"

[project.entry-points."pandas.Series.accessor"]
<name> = "<module>:<AccessorClass>"

Comment on lines +408 to +426
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Much of this doc should really go here:
https://pandas.pydata.org/pandas-docs/stable/development/extending.html#registering-custom-accessors

And that doc should be updated accordingly.

[project.entry-points."pandas.Index.accessor"]
<name> = "<module>:<AccessorClass>"

For more information about entrypoints:
https://packaging.python.org/en/latest/guides/creating-and-discovering-plugins/#plugin-entry-points


For each valid entry point:
- The accessor class is dynamically imported and registered using
the appropriate registration decorator function
(e.g. register_dataframe_accessor).
- If two packages declare the same accessor name, a warning is issued,
and only the first one is used.

Notes
-----
- This function is only intended to be called at pandas startup.
- For more information about accessors read their documentation.

Raises
------
UserWarning
If two accessors share the same name, the second one is ignored.

Examples
--------
# setup.py
entry_points={
'pandas.DataFrame.accessor': [
'myplugin = myplugin.accessor:MyPluginAccessor',
],
}
# END setup.py

- That entrypoint would allow the following code:

import pandas as pd

df = pd.DataFrame({"A": [1, 2, 3]})
df.myplugin.do_something() # Calls MyPluginAccessor.do_something()
"""

ACCESSOR_REGISTRY_FUNCTIONS: dict[str, Callable] = {
"pandas.DataFrame.accessor": register_dataframe_accessor,
"pandas.Series.accessor": register_series_accessor,
"pandas.Index.accessor": register_index_accessor,
}

pd_objects_entrypoints: list[str] = ACCESSOR_REGISTRY_FUNCTIONS.keys()

for pd_obj_entrypoint in pd_objects_entrypoints:
accessors: EntryPoints = entry_points(group=pd_obj_entrypoint)
accessor_package_dict: dict[str, str] = {}

for new_accessor in accessors:
dist = getattr(new_accessor, "dist", None)
new_pkg_name = getattr(dist, "name", "Unknown") if dist else "Unknown"

# Verifies duplicated accessor names
if new_accessor.name in accessor_package_dict:
loaded_pkg_name: str = accessor_package_dict.get(
new_accessor.name, "Unknown"
)

warnings.warn(
"Warning: you have two accessors with the same name:"
f" '{new_accessor.name}' has already been registered"
f" by the package '{new_pkg_name}'. The "
f"'{new_accessor.name}' provided by the package "
f"'{loaded_pkg_name}' is not being used. "
"Uninstall the package you don't want"
"to use if you want to get rid of this warning.\n",
UserWarning,
stacklevel=2,
)

accessor_package_dict.update({new_accessor.name: new_pkg_name})

def make_accessor(ep):
return lambda self, ep=ep: ep.load()(self)

register_fn = ACCESSOR_REGISTRY_FUNCTIONS.get(pd_obj_entrypoint)

if register_fn is not None:
register_fn(new_accessor.name)(make_accessor(new_accessor))
Loading
Loading