Skip to content

FIX (SLEP6) descriptor shouldn't override method - #32111

Merged
adrinjalali merged 44 commits into
scikit-learn:mainfrom
adrinjalali:slep6/override
May 19, 2026
Merged

adrinjalali merged 44 commits into
scikit-learn:mainfrom
adrinjalali:slep6/override

Conversation

@adrinjalali

Copy link
Copy Markdown
Member

If a class implements a set_{method}_request explicitly (like done in scorers), then the descriptor shouldn't be overriding it.

xref: #30859 (comment)

cc @antoinebaker @OmarManzoor

This fixes some existing issues. The added tests should represent where things were failing.

adrinjalali and others added 30 commits June 12, 2025 15:03
Co-authored-by: Stefanie Senger <[email protected]>
@adrinjalali adrinjalali added this to Labs Dec 9, 2025
@github-project-automation github-project-automation Bot moved this to Todo in Labs Dec 9, 2025
@adrinjalali adrinjalali moved this from Todo to In progress in Labs Dec 9, 2025
@adrinjalali adrinjalali self-assigned this Dec 9, 2025
@adrinjalali adrinjalali moved this from In progress to Todo in Labs Dec 9, 2025
@adrinjalali adrinjalali removed their assignment Dec 11, 2025
@jeremiedbb jeremiedbb added the Metadata Routing all issues related to metadata routing, slep006, sample props label Apr 5, 2026
@github-actions github-actions Bot added the CI:Linter failure The linter CI is failing on this PR label May 18, 2026

@adrinjalali adrinjalali left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Thanks for the careful review, @StefanieSenger, and for actually rebuilding to check. Your observation is correct as far as main alone goes: LogisticRegressionCV.set_score_request() looks the same with and without this PR, because LogisticRegressionCV.score itself still declares sample_weight. The visible change for LogisticRegressionCV only materializes once #30859 lands, which is the reason this PR exists.

The chain is:

  • In #30859-disussion, LogisticRegressionCV gets __metadata_request__score = {"sample_weight": metadata_routing.UNUSED} (with a TODO(1.9): remove this when sample_weight is removed from the score signature).
  • @antoinebaker then noticed that, even with that marker, LogisticRegressionCV().set_score_request still accepts sample_weight.
  • The reason is in _MetadataRequester.__init_subclass__: the UNUSED marker leaves requests empty, main's if not requests: continue short-circuits, no descriptor is installed on LogisticRegressionCV, and so it inherits LogisticRegression's set_score_request which defeats the marker.
  • This PR fixes that: when requests is empty but the class would inherit a RequestMethod from a parent, install an empty RequestMethod to shadow it.

The same code path also covers the second case — a class that defines set_{method}_request by hand (as _BaseScorer does, and third-party scorers / estimators may do). On main, any subclass whose method exposes metadata would overwrite the explicit definition with a generated descriptor; with this PR the explicit method is detected via inspect.getattr_static and left alone. You're right that, today in-tree, no class other than _BaseScorer defines set_score_request explicitly and no in-tree scorer subclass has a score with metadata, so this branch is mostly there for third-party libraries and forward compatibility.

The reproducer below stitches both into a single script. It works against this branch alone by (a) simulating #30859 with a LogisticRegressionCV subclass that carries the UNUSED marker, and (b) monkey-patching _MetadataRequester.__init_subclass__ back to main's body so you can see the contrast in the same process.

Reproducer (Python)
import inspect
from sklearn import set_config
set_config(enable_metadata_routing=True)

from sklearn.base import BaseEstimator
from sklearn.linear_model import LogisticRegressionCV
from sklearn.utils import metadata_routing
from sklearn.utils._metadata_requests import (
    _MetadataRequester, RequestMethod, SIMPLE_METHODS,
)


def run_scenarios(label):
    print(f"\n--- {label} ---")

    # Case 1: the actual #30859 scenario — UNUSED marker on a subclass whose
    # parent's score() accepts sample_weight.
    class LR_CV_30859(LogisticRegressionCV):
        __metadata_request__score = {
            "sample_weight": metadata_routing.UNUSED,
        }

    print("Case 1 (#30859: LR_CV + __metadata_request__score = UNUSED):")
    print(f"  parent  params: {list(inspect.signature(LogisticRegressionCV.set_score_request).parameters)[1:]}")
    print(f"  subclass params: {list(inspect.signature(LR_CV_30859.set_score_request).parameters)[1:]}")

    # Case 2: a parent defines set_score_request explicitly (third-party / _BaseScorer style).
    class P(BaseEstimator):
        def set_score_request(self, sample_weight=None, metadata=None):
            return self

    class C(P):
        def score(self, X, y, sample_weight=None):
            return 0

    print("Case 2 (explicit method on parent):")
    print(f"  P.set_score_request kind: {type(P.__dict__['set_score_request']).__name__}")
    print(f"  C.set_score_request kind: "
          f"{type(C.__dict__.get('set_score_request')).__name__}  (None == inherited)")


# 1) Run with this PR's logic.
run_scenarios("with PR #32111")

# 2) Restore main's pre-fix __init_subclass__ and run again.
def main_init_subclass(cls, **kwargs):
    try:
        for method in SIMPLE_METHODS:
            requests = cls._get_class_level_metadata_request_values(method)
            if not requests:
                continue
            setattr(cls, f"set_{method}_request",
                    RequestMethod(method, sorted(requests)))
    except Exception:
        pass
    super(_MetadataRequester, cls).__init_subclass__(**kwargs)

_MetadataRequester.__init_subclass__ = classmethod(main_init_subclass)
run_scenarios("with main (pre-fix logic)")

Output on this branch:

--- with PR #32111 ---
Case 1 (#30859: LR_CV + __metadata_request__score = UNUSED):
  parent  params: ['sample_weight']
  subclass params: []
Case 2 (explicit method on parent):
  P.set_score_request kind: function
  C.set_score_request kind: NoneType  (None == inherited)

--- with main (pre-fix logic) ---
Case 1 (#30859: LR_CV + __metadata_request__score = UNUSED):
  parent  params: ['sample_weight']
  subclass params: ['sample_weight']                 # UNUSED ignored
Case 2 (explicit method on parent):
  P.set_score_request kind: function
  C.set_score_request kind: RequestMethod            # parent's explicit method shadowed

So short version: on plain main, you won't see a LogisticRegressionCV.set_score_request docstring change from this PR: your observation is correct. The change is invisible until #30859's __metadata_request__score = UNUSED ships. The two PRs are paired: this one makes the UNUSED marker actually take effect across inheritance.

.. [1] https://www.python.org/dev/peps/pep-0487
"""

def is_RequestMethod(obj, name: str):

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

this is inside a function, and not exposed to the user, so doesn't matter what it's called.

Comment on lines +1452 to +1454
def is_RequestMethod(obj, name: str):
value = inspect.getattr_static(obj, name)
return isinstance(value, RequestMethod)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

getattr_static is very different from going through the MRO, so I don't think they can be merged.


try:
for method in SIMPLE_METHODS:
set_method_name = f"set_{method}_request"

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

it's the method name though, not a method request.

Comment thread sklearn/utils/_metadata_requests.py Outdated
# metadata with an UNUSED marker, and that the parent class has
# the method already. In this case, we cannot remove the method
# since it exists in the parent class, and instead we set it with
# an empty set of requests.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

right, updated where the comment goes + added a comment here.

@github-actions github-actions Bot removed the CI:Linter failure The linter CI is failing on this PR label May 18, 2026

@StefanieSenger StefanieSenger left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for your comments and adjustments, @adrinjalali.

I had another look and I think this is alright, but I've made a suggestion for readability in __init_subclass__ by adding helper functions. Also the comments are a bit off.

Apart from this, it's fine, also the tests and I have approved.

Comment thread sklearn/utils/_metadata_requests.py Resolved
Comment thread sklearn/utils/_metadata_requests.py Resolved
@adrinjalali
adrinjalali enabled auto-merge (squash) May 19, 2026 13:10
@adrinjalali
adrinjalali merged commit c3be4fc into scikit-learn:main May 19, 2026
31 checks passed
@github-project-automation github-project-automation Bot moved this from Todo to Done in Labs May 19, 2026
@jeremiedbb jeremiedbb added this to the 1.9 milestone May 19, 2026
@jeremiedbb jeremiedbb added the To backport PR merged in master that need a backport to a release branch defined based on the milestone. label May 19, 2026
@adrinjalali
adrinjalali deleted the slep6/override branch May 19, 2026 13:53
@jeremiedbb jeremiedbb mentioned this pull request Jun 1, 2026
16 tasks done
jeremiedbb pushed a commit that referenced this pull request Jun 2, 2026
Co-authored-by: Omar Salman <[email protected]>
Co-authored-by: Stefanie Senger <[email protected]>
Co-authored-by: Omar Salman <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Metadata Routing all issues related to metadata routing, slep006, sample props module:utils To backport PR merged in master that need a backport to a release branch defined based on the milestone.

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

4 participants