Skip to content

Connection to TypeVar bound to Union is lost after returning Self from method #16826

Open

Description

@exoriente

Bug Report

A variable of which the type is determined by a TypeVar can normally return an object of type Self from a method and have the returned object recognized as an instance of the TypeVar type. This no longer works of the TypeVar is bound to a Union, even if the method always returns a Self object for every type in the Union.

To Reproduce

from typing import Self, TypeVar


class A:
    def new_version(self) -> Self:
        return self


class B:
    def new_version(self) -> Self:
        return self


T = TypeVar("T", bound=A)
S = TypeVar("S", bound=A | B)


def f(x: T) -> T:
    return x.new_version()


def g(x: S) -> S:
    return x.new_version()

Mypy playground gist: https://mypy-play.net/?mypy=latest&python=3.12&gist=5e9aa0a21d090f7f21e4e3b643cd9941

Expected Behavior

mypy should approve both function f and g.

Actual Behavior

mypy considers function g to be erroneous:

main.py:23: error: Incompatible return value type (got "A | B", expected "S")  [return-value]

Your Environment

  • Mypy version used: 1.8.0
  • Mypy command-line flags: None
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: 3.12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions