python / python/mypy

Mypy rejects `cls.__repr__(obj)` when `cls: type[Any]`

Open
#16,212 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Mypy accepts this:

object.__repr__(123)  # type-checks

cls: type[object]
cls.__repr__(123)  # also type-checks

But rejects this:

cls: type[Any]
cls.__repr__(123)  #  Too many arguments for "__repr__" of "object"  [call-arg]

Expected Behavior

I expected mypy to accept cls.__repr__(obj) even when cls: type[Any]. In particular, I expected type[Any] to be more permissive than type[object], not less.

Your Environment

Tested with mypy master branch + Python 3.11 using mypy-play.

Context

I currently have this running in production:

def _robust_repr(obj: object) -> str:
    cls: Type[object]  # Had to add this to suppress the typecheck error
    for cls in type(obj).__mro__:
        with suppress(Exception):
            return cls.__repr__(obj)
    assert False  # object.__repr__ can't fail

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 two __repr__ calls and the cls: type[Any] case in mypy-play using the Python 3.11 examples from the issue. Trace the type-checking path for type[Any] member access and confirm that cls.__repr__(obj) is accepted without changing the valid type[object] behavior.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.