python / python/mypy

False negative for restricted self in subclass

Open
#7,861 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug priority-1-normal topic-inheritance topic-self-types
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

This currently passes, but the code is unsafe:

from typing import TypeVar, Generic

T = TypeVar('T')

class Base(Generic[T]):
    def __init__(self, item: T) -> None:
        self.item = item
    def foo(self) -> None:
        pass

class Sub(Base[T]):
    def foo(self: Sub[str]) -> None:
        self.item + 'no'

# This is why the above is unsafe.
a: Base[int] = Sub(0)
a.foo()

On one hand it is a very rare situation, on the other hand in view of making explicit self-types a more "official" feature (see https://github.com/python/mypy/pull/7860) we might want to fix this.

Also it would be great to fix this in a consistent way, so that the fix also works for same issue with multiple inheritance without code duplication (see https://github.com/python/mypy/issues/7724).

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

Start by reproducing the example in the issue, then read the explicit self-type work in PR 7860 and the multiple-inheritance case in issue 7724. The fix should consistently reject this unsafe subclass usage and cover the corresponding multiple-inheritance behavior without duplicated logic.

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.