python / python/mypy

`self` annotation not checked in `__index__`?

Open
#19,341 3 comments 3 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-calls topic-protocols topic-self-types
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

To Reproduce

from __future__ import annotations
from typing import Callable, TypeVar, Any, Protocol, Self, Any

T = TypeVar('T', covariant=True)

class Array(Protocol[T]):
    def __index__(self: Array[int], /) -> int: ...
    def dtype(self) -> T: ...
    def __rmul__(self, other: Any) -> Self: ...

def func(a: Array[str], b: list[bool]) -> None:
    result = b * a
    reveal_type(result)

https://mypy-play.net/?mypy=latest&python=3.12&gist=596075fa56c1bd714ec44b224f5ed97c

Expected Behavior

t.py:13: note: Revealed type is "Array[str]"

(which is what Pyright does)

This is because list.__mul__ is defined as

https://github.com/python/typeshed/blob/7aad2554355b55e70e4137fadf48f294ee79efaf/stdlib/builtins.pyi#L1124

    def __mul__(self, value: SupportsIndex, /) -> list[_T]: ...

and SupportsIndex checks for __index__(self) -> int, and if value is Array[str], then Array.__index__ is not matched

Actual Behavior

t.py:13: note: Revealed type is "builtins.list[builtins.bool]"

Your Environment

  • Mypy version used: 1.16.1
  • Mypy command-line flags:
  • Mypy configuration options from mypy.ini (and other config files):
  • Python version used: 3.12

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Reproduce the example in the issue with Python 3.12 and mypy 1.16.1, checking the revealed type for b * a. Trace how the self annotation on Array.index is matched against SupportsIndex and list.mul. Done means the example reveals Array[str] as expected and has regression coverage.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.