-
-
Notifications
You must be signed in to change notification settings - Fork 18.6k
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
base: main
Are you sure you want to change the base?
Changes from 6 commits
9962904
ded0b0d
f2a036e
fcfa155
678b2dc
2793f91
01a1bfc
2807683
d2066a1
03885c5
001c05a
1013934
95b7a5c
0eb5bc1
1c5ac85
63e4882
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
TODO | ||
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -346,3 +346,8 @@ | |
"unique", | ||
"wide_to_long", | ||
] | ||
|
||
from pandas.core.accessor import DataFrameAccessorLoader | ||
|
||
DataFrameAccessorLoader.load() | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 There was a problem hiding this comment. Choose a reason for hiding this commentThe 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? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
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. There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -10,6 +10,7 @@ | |
import functools | ||
from typing import ( | ||
TYPE_CHECKING, | ||
Any, | ||
final, | ||
) | ||
import warnings | ||
|
@@ -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() | ||
|
@@ -393,3 +396,39 @@ 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.""" | ||
PedroM4rques marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
ENTRY_POINT_GROUP: str = "pandas_dataframe_accessor" | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 There was a problem hiding this comment. Choose a reason for hiding this commentThe 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
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 |
||
|
||
@classmethod | ||
def load(cls) -> None: | ||
"""loads and registers accessors defined by 'pandas_dataframe_accessor'.""" | ||
eps = entry_points(group=cls.ENTRY_POINT_GROUP) | ||
names: set[str] = set() | ||
PedroM4rques marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
for ep in eps: | ||
name: str = ep.name | ||
|
||
if name in names: # Verifies duplicated package names | ||
warnings.warn( | ||
f"Warning: you have two packages with the same name: '{name}'. " | ||
PedroM4rques marked this conversation as resolved.
Show resolved
Hide resolved
|
||
"Uninstall the package you don't want to use " | ||
"in order to remove this warning.\n", | ||
UserWarning, | ||
stacklevel=2, | ||
) | ||
|
||
else: | ||
names.add(name) | ||
|
||
def make_property(ep): | ||
def accessor(self) -> Any: | ||
cls_ = ep.load() | ||
return cls_(self) | ||
|
||
return accessor | ||
|
||
register_dataframe_accessor(name)(make_property(ep)) |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,227 @@ | ||
import pandas as pd | ||
import pandas._testing as tm | ||
from pandas.core.accessor import DataFrameAccessorLoader | ||
|
||
|
||
def test_no_accessors(monkeypatch): | ||
# GH29076 | ||
|
||
# Mock entry_points | ||
def mock_entry_points(*, group): | ||
return [] | ||
|
||
# Patch entry_points in the correct module | ||
monkeypatch.setattr("pandas.core.accessor.entry_points", mock_entry_points) | ||
|
||
DataFrameAccessorLoader.load() | ||
|
||
|
||
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" | ||
|
||
|
||
def test_duplicate_accessor_names(monkeypatch): | ||
# GH29076 | ||
# Create plugin | ||
class MockEntryPoint1: | ||
name = "duplicate_accessor" | ||
|
||
def load(self): | ||
class Accessor1: | ||
def __init__(self, df): | ||
self._df = df | ||
|
||
def which(self): | ||
return "Accessor1" | ||
|
||
return Accessor1 | ||
|
||
# Create plugin | ||
class MockEntryPoint2: | ||
name = "duplicate_accessor" | ||
|
||
def load(self): | ||
class Accessor2: | ||
def __init__(self, df): | ||
self._df = df | ||
|
||
def which(self): | ||
return "Accessor2" | ||
|
||
return Accessor2 | ||
|
||
def mock_entry_points(*, group): | ||
if group == DataFrameAccessorLoader.ENTRY_POINT_GROUP: | ||
return [MockEntryPoint1(), MockEntryPoint2()] | ||
return [] | ||
|
||
monkeypatch.setattr("pandas.core.accessor.entry_points", mock_entry_points) | ||
|
||
# Check that the UserWarning is raised | ||
with tm.assert_produces_warning(UserWarning, match="duplicate_accessor") as record: | ||
DataFrameAccessorLoader.load() | ||
|
||
messages = [str(w.message) for w in record] | ||
assert any("two packages with the same name" in msg for msg in messages) | ||
|
||
df = pd.DataFrame({"x": [1, 2, 3]}) | ||
assert hasattr(df, "duplicate_accessor") | ||
assert df.duplicate_accessor.which() in {"Accessor1", "Accessor2"} | ||
|
||
|
||
def test_unique_accessor_names(monkeypatch): | ||
# GH29076 | ||
# Create plugin | ||
class MockEntryPoint1: | ||
name = "accessor1" | ||
|
||
def load(self): | ||
class Accessor1: | ||
def __init__(self, df): | ||
self._df = df | ||
|
||
def which(self): | ||
return "Accessor1" | ||
|
||
return Accessor1 | ||
|
||
# Create plugin | ||
class MockEntryPoint2: | ||
name = "accessor2" | ||
|
||
def load(self): | ||
class Accessor2: | ||
def __init__(self, df): | ||
self._df = df | ||
|
||
def which(self): | ||
return "Accessor2" | ||
|
||
return Accessor2 | ||
|
||
def mock_entry_points(*, group): | ||
if group == DataFrameAccessorLoader.ENTRY_POINT_GROUP: | ||
return [MockEntryPoint1(), MockEntryPoint2()] | ||
return [] | ||
|
||
monkeypatch.setattr("pandas.core.accessor.entry_points", mock_entry_points) | ||
|
||
# Check that no UserWarning is raised | ||
with tm.assert_produces_warning(None, check_stacklevel=False): | ||
DataFrameAccessorLoader.load() | ||
|
||
df = pd.DataFrame({"x": [1, 2, 3]}) | ||
assert hasattr(df, "accessor1"), "Accessor1 not registered" | ||
assert hasattr(df, "accessor2"), "Accessor2 not registered" | ||
assert df.accessor1.which() == "Accessor1", "Accessor1 method incorrect" | ||
assert df.accessor2.which() == "Accessor2", "Accessor2 method incorrect" | ||
|
||
|
||
def test_duplicate_and_unique_accessor_names(monkeypatch): | ||
# GH29076 | ||
# Create plugin | ||
class MockEntryPoint1: | ||
name = "duplicate_accessor" | ||
|
||
def load(self): | ||
class Accessor1: | ||
def __init__(self, df): | ||
self._df = df | ||
|
||
def which(self): | ||
return "Accessor1" | ||
|
||
return Accessor1 | ||
|
||
# Create plugin | ||
class MockEntryPoint2: | ||
name = "duplicate_accessor" | ||
|
||
def load(self): | ||
class Accessor2: | ||
def __init__(self, df): | ||
self._df = df | ||
|
||
def which(self): | ||
return "Accessor2" | ||
|
||
return Accessor2 | ||
|
||
# Create plugin | ||
class MockEntryPoint3: | ||
name = "unique_accessor" | ||
|
||
def load(self): | ||
class Accessor3: | ||
def __init__(self, df): | ||
self._df = df | ||
|
||
def which(self): | ||
return "Accessor3" | ||
|
||
return Accessor3 | ||
|
||
def mock_entry_points(*, group): | ||
if group == DataFrameAccessorLoader.ENTRY_POINT_GROUP: | ||
return [MockEntryPoint1(), MockEntryPoint2(), MockEntryPoint3()] | ||
return [] | ||
|
||
monkeypatch.setattr("pandas.core.accessor.entry_points", mock_entry_points) | ||
|
||
# Capture warnings | ||
with tm.assert_produces_warning(UserWarning, match="duplicate_accessor") as record: | ||
DataFrameAccessorLoader.load() | ||
|
||
messages = [str(w.message) for w in record] | ||
|
||
# Filter warnings for the specific message about duplicate packages | ||
duplicate_package_warnings = [ | ||
msg | ||
for msg in messages | ||
if "you have two packages with the same name: 'duplicate_accessor'" in msg | ||
] | ||
|
||
# Assert one warning about duplicate packages | ||
assert len(duplicate_package_warnings) == 1, ( | ||
f"Expected exactly one warning about duplicate packages, " | ||
f"got {len(duplicate_package_warnings)}: {duplicate_package_warnings}" | ||
) | ||
|
||
df = pd.DataFrame({"x": [1, 2, 3]}) | ||
assert hasattr(df, "duplicate_accessor"), "duplicate_accessor not registered" | ||
|
||
assert hasattr(df, "unique_accessor"), "unique_accessor not registered" | ||
|
||
assert df.duplicate_accessor.which() in {"Accessor1", "Accessor2"}, ( | ||
"duplicate_accessor method incorrect" | ||
) | ||
assert df.unique_accessor.which() == "Accessor3", "unique_accessor method incorrect" |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is the main document you want to update: https://pandas.pydata.org/docs/development/extending.html
Probably a comment here too: https://pandas.pydata.org/docs/reference/series.html#accessors (and for dataframe and index maybe).
I think for most users, if they are using a package providing an accessor, they'll already get the idea on how this works from the package documentation.