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 17 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Feat: compatible with multiple pandas objects accessors (df, series, …
…idx)

- Improved docstrs
- Improved tests
- Improved whatsnew entry

Co-authored-by: Afonso Antunes <[email protected]>
  • Loading branch information
PedroM4rques and afonso-antunes committed Jun 15, 2025
commit 101393418f82e557a76266640f8ddc9d4e699a0a
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v3.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +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` plugin accessor via entry points (:issue:`29076`)
- 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
133 changes: 83 additions & 50 deletions pandas/core/accessor.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
import functools
from typing import (
TYPE_CHECKING,
Any,
final,
)
import warnings
Expand Down Expand Up @@ -405,17 +404,31 @@ def accessor_entry_point_loader() -> None:
"""
Load and register pandas accessors declared via entry points.

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

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

For example:
OR for pyproject.toml file:

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

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

[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:
Expand All @@ -428,6 +441,7 @@ def accessor_entry_point_loader() -> None:
Notes
-----
- This function is only intended to be called at pandas startup.
- For more information about accessors read their documentation.

Raises
------
Expand All @@ -436,48 +450,67 @@ def accessor_entry_point_loader() -> None:

Examples
--------
df.myplugin.do_something() # Assuming such accessor was registered
"""

ENTRY_POINT_GROUP: str = "pandas.accessor"

accessors: EntryPoints = entry_points(group=ENTRY_POINT_GROUP)
accessor_package_dict: dict[str, str] = {}

for new_accessor in accessors:
if new_accessor.dist is not None:
# Try to get new_accessor.dist.name,
# if that's not possible: new_pkg_name = 'Unknown'
new_pkg_name: str = getattr(new_accessor.dist, "name", "Unknown")
else:
new_pkg_name: str = "Unknown"
# setup.py
entry_points={
'pandas.DataFrame.accessor': [
'myplugin = myplugin.accessor:MyPluginAccessor',
],
}
# END setup.py

# Verifies duplicated accessor names
if new_accessor.name in accessor_package_dict:
loaded_pkg_name: str = accessor_package_dict.get(new_accessor.name)
- That entrypoint would allow the following code:

if loaded_pkg_name is None:
loaded_pkg_name = "Unknown"
import pandas as pd

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}'. So 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):
def accessor(self) -> Any:
cls_ = ep.load()
return cls_(self)

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

register_dataframe_accessor(new_accessor.name)(make_accessor(new_accessor))
PD_OBJECTS_ENTRYPOINTS: list[str] = [
"pandas.DataFrame.accessor",
"pandas.Series.accessor",
"pandas.Index.accessor",
]

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

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)

if loaded_pkg_name is None:
loaded_pkg_name: str = "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