Skip to content

Fix overload inference with protocol __class__ overrides - #21896

Open
daleselaji-dev wants to merge 1 commit into
python:masterfrom
daleselaji-dev:codex/fix-class-override-21795
Open

Fix overload inference with protocol __class__ overrides#21896
daleselaji-dev wants to merge 1 commit into
python:masterfrom
daleselaji-dev:codex/fix-class-override-21795

Conversation

@daleselaji-dev

Copy link
Copy Markdown

Problem

When a protocol overrides __class__, overload inference can select an incompatible overload. A concrete list[int] was incorrectly inferred as matching a protocol overload parameterized with str, so the call result was revealed as str instead of int.

Root Cause

Protocol constraint inference treated the synthetic __class__ member as a normal structural member. Because every object exposes __class__, its concrete class object could contribute an unrelated constraint for the protocol type variable and distort overload selection.

Solution

Ignore __class__ when inferring type-variable constraints from protocol members. It remains available for normal member lookup and structural compatibility checks; it is excluded only from constraint generation, where it cannot provide a useful protocol relationship.

Changes

  • Skip __class__ in infer_constraints_from_protocol_members.
  • Add a regression test covering protocol overload resolution with a __class__ override.

Testing

  • py -3.10 -m pytest -n0 -q mypy/test/testsubtypes.py -k protocol_overload_with_class_override (passed: 1)
  • py -3.10 -m pytest -n0 -q mypy/test/testsubtypes.py (passed: 27)
  • py -3.10 -m black --check mypy/constraints.py mypy/test/testsubtypes.py (passed)
  • py -3.10 -m ruff check mypy/constraints.py mypy/test/testsubtypes.py (passed)
  • py -3.10 -m compileall -q mypy/constraints.py mypy/test/testsubtypes.py (passed)
  • git diff --check (passed)
  • pre-commit was attempted but could not complete because the first-time actionlint environment download returned BadZipFile; this remains unverified.

Compatibility/Risk

The change is limited to protocol constraint inference and does not alter runtime behavior. The main risk is an unexpected effect on a protocol that intentionally relies on __class__ for type-variable inference; the regression test and full subtype suite cover the affected path.

Notes for Reviewer

Please review whether __class__ should be excluded from protocol constraint inference globally or only for this overload-inference path, and consider adding any project-specific edge cases to the subtype test suite.

Linked Issue

Closes #21795

@daleselaji-dev
daleselaji-dev marked this pull request as ready for review August 27, 2026 03:42
@github-actions

Copy link
Copy Markdown
Contributor

According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

1 participant