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 4 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` plugin accessor 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 pandas.core.accessor import DataFrameAccessorLoader

DataFrameAccessorLoader.load()
Copy link
Member

Choose a reason for hiding this comment

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

Why a class with a single method?

And why only doing this for DataFrame, not for Series?

Copy link

@afonso-antunes afonso-antunes Jun 3, 2025

Choose a reason for hiding this comment

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

Me and @PedroM4rques are currently planning to use this for a third-party accessor related to Vaex (see related discussion in issue #29076 . Our main motivation is to provide a structured and maintainable way to register external accessors without cluttering the core codebase.

We initially opted for a class with a single method (load) mostly as a pragmatic choice, since we're not yet deeply familiar with all the internals of Pandas. It seemed like a clean and extensible way to isolate the registration logic. That said, if a standalone function would be preferred, we’re absolutely open to changing it.

Regarding the focus on DataFrame only: we started with that use case since it was our immediate need, but extending this to Series or other objects makes sense and could certainly be part of the plan going forward. Would you recommend covering that already in this PR?

Copy link
Contributor

Choose a reason for hiding this comment

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

Would you recommend covering that already in this PR?

Yes, I'd say so. It won't be much more complicated and any libraries that provide both Series and DataFrame accessors wanting to will want these at the same time.

Copy link
Member

Choose a reason for hiding this comment

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

We should probably add the same for Index too.

Better to use a function than class with a single method. I doubt it'll never have more methods, but if it does, we can always change later, as this is private.

del DataFrameAccessorLoader
26 changes: 26 additions & 0 deletions pandas/core/accessor.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import functools
from typing import (
TYPE_CHECKING,
Any,
final,
)
import warnings
Expand All @@ -25,6 +26,8 @@
from pandas import Index
from pandas.core.generic import NDFrame

from importlib.metadata import entry_points


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

return _register_accessor(name, Index)


class DataFrameAccessorLoader:
"""Loader class for registering DataFrame accessors via entry points."""

ENTRY_POINT_GROUP: str = "pandas_dataframe_accessor"
Copy link
Member

Choose a reason for hiding this comment

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

I don't think we want different entrypoints for each data type, so pandas_accessor should be better.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Now that we want to implement an entrypoint system for every pandas obj (df, series, idx), we came across a problem: not all accessors are compatible with every pandas obj.

To address this, our plugin system needs a way to declare explicitly which object types each accessor supports.

That said, here's our documentation of the new loader function accessor_entry_point_loader() that explains what we are thinking:

    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>, ... ],
        }

        # pyproject.toml
        TODO
        TODO
        TODO


    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()

Copy link
Contributor

Choose a reason for hiding this comment

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

I think separate entry points for separate accessors is probably needed.

I would mention pyproject.toml rather than setup.py and link to https://packaging.python.org/en/latest/guides/creating-and-discovering-plugins/#plugin-entry-points.


@classmethod
def load(cls) -> None:
"""loads and registers accessors defined by 'pandas_dataframe_accessor'."""
eps = entry_points(group=cls.ENTRY_POINT_GROUP)

for ep in eps:
name: str = ep.name

def make_property(ep):
def accessor(self) -> Any:
cls_ = ep.load()
return cls_(self)

return accessor

register_dataframe_accessor(name)(make_property(ep))
35 changes: 35 additions & 0 deletions pandas/tests/test_plugis_entrypoint_loader.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import pandas as pd
from pandas.core.accessor import DataFrameAccessorLoader


def test_load_dataframe_accessors(monkeypatch):
# GH29076
# Mocked EntryPoint to simulate a plugin
class MockEntryPoint:
name = "test_accessor"

def load(self):
class TestAccessor:
def __init__(self, df):
self._df = df

def test_method(self):
return "success"

return TestAccessor

# Mock entry_points
def mock_entry_points(*, group):
if group == DataFrameAccessorLoader.ENTRY_POINT_GROUP:
return [MockEntryPoint()]
return []

# Patch entry_points in the correct module
monkeypatch.setattr("pandas.core.accessor.entry_points", mock_entry_points)

DataFrameAccessorLoader.load()

# Create DataFrame and verify that the accessor was registered
df = pd.DataFrame({"a": [1, 2, 3]})
assert hasattr(df, "test_accessor")
assert df.test_accessor.test_method() == "success"
Loading