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 16 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
56 changes: 56 additions & 0 deletions doc/source/development/extending.rst
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,62 @@ For a ``Series`` accessor, you should validate the ``dtype`` if the accessor
applies only to certain dtypes.


Registering accessors via entry points
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

You can create a custom accessor for a pandas object and expose it via Python's
entry point system. Once installed using pip, the accessor can be automatically
discovered and registered by pandas at runtime, without requiring manual import.

To register the entry point for your accessor, follow the format shown below:

.. code-block:: python

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

Alternatively, if you are using a ``pyproject.toml``-based build:

.. code-block:: none

# 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>"


Assuming the accessor class ``GeoAccessor`` is defined in the module
``geoPlugin.geo_accessor``, and using the accessor name ``geo`` as in the
example above:

.. code-block:: python

# setup.py
entry_points={
'pandas.DataFrame.accessor': [ 'geo = geoPlugin.geo_accessor:GeoAccessor' ],
}

Or, for a ``pyproject.toml``-based build:

.. code-block:: toml

# pyproject.toml
[project.entry-points."pandas.DataFrame.accessor"]
geo = "geoPlugin.geo_accessor:GeoAccessor"


For background on Python's Entry Point system and Plugins:
https://packaging.python.org/en/latest/guides/creating-and-discovering-plugins/#plugin-entry-points

.. _extending.extension-types:

Extension types
Expand Down
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
124 changes: 124 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,122 @@ 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. These accessors extend
core pandas objects (`DataFrame`, `Series`, `Index`).

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 using pyproject.toml file:

# 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 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, refer to:
- Pandas documentation on extending accessors:
https://pandas.pydata.org/docs/development/extending.html#registering-custom-accessors
- Series accessor API reference:
https://pandas.pydata.org/docs/reference/series.html#accessors
- Note: DataFrame and Index accessors (e.g., `.sparse`, `.str`) use the same
mechanism but are not listed in separate reference pages as of now.

- For background on Python plugin entry points:
https://packaging.python.org/en/latest/guides/creating-and-discovering-plugins/#plugin-entry-points

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_OBJ_ENTRYPOINTS: tuple[str, ...] = tuple(ACCESSOR_REGISTRY_FUNCTIONS.keys())

for pd_obj_entrypoint in PD_OBJ_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