python / python/mypy

Self type is not expanded correctly when accessed on a type variable with union bound

Open
#19,584 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-self-types topic-type-variables topic-union-types
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description


from typing import Self, TypeVar, reveal_type

class A:
    def f(self,) -> Self:
        return self

class B:
    def f(self,) -> Self:
        return self

T = TypeVar('T', bound=A | B)

def g(arg: T) -> T:
    result = arg.f()
    reveal_type(result)
    return result

produces

narrow_self.py:15: note: Revealed type is "narrow_self.A | narrow_self.B"
narrow_self.py:16: error: Incompatible return value type (got "A | B", expected "T")  [return-value]

This should be safe because arg.f() returns Self which is T in this case.

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 running the provided narrow_self.py example and inspecting how the type checker expands Self for a TypeVar bound to a union. Trace the relevant Self and union-bound handling, then verify that reveal_type(result) preserves T and that the return is accepted without an error.

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.