mypy icon indicating copy to clipboard operation
mypy copied to clipboard

mypy loses information about types. 'str | tuple[str, ...]' becomes 'Sequence[str]'

Open iharabukhouski opened this issue 7 months ago • 3 comments

Bug Report

mypy loses information about types. 'str | tuple[str, ...]' becomes 'Sequence[str]'

To Reproduce

version 1: this fails

from typing import TypeVar

T = TypeVar('T')

def unwrap(x: T | None) -> T:

  assert x is not None

  return x

class Qux:

    def foo(self) -> str | tuple[str, ...]:

        baz = unwrap(self.bar())

        return baz

    def bar(self) -> str | tuple[str, ...] | None:

        return 'quux'

version 2: this works

class Qux:

    def foo(self) -> str | tuple[str, ...]:

        baz = self.bar()

        assert baz is not None

        return baz

    def bar(self) -> str | tuple[str, ...] | None:

        return 'quux'

Expected Behavior

both versions of code should run successfully

Actual Behavior

version 2 fails with the following error: 'Incompatible return value type (got "Sequence[str]", expected "str | tuple[str, ...]") [return-value]'

Your Environment

mypy version: 1.15.0 python version: 3.12

reproducible even the mypy playground

iharabukhouski avatar Jun 02 '25 23:06 iharabukhouski

Working playground link: https://mypy-play.net/?mypy=master&python=3.12&gist=525c6298e4a1367cfba7fc00d042feea

This is another example of #12025, just with different common ancestor: str and tuple[str] are both Sequence[str], usually this manifests as object type in unexpected places, here it's a bit more friendly.

sterliakov avatar Jun 03 '25 00:06 sterliakov

@sterliakov #12025 seems to be merged. does it mean that the issue is already fixed?

iharabukhouski avatar Jun 07 '25 18:06 iharabukhouski

Damn, sorry, I typoed or copied wrong issue number... That should be #12056, a long-standing issue that isn't resolved yet.

sterliakov avatar Jun 07 '25 18:06 sterliakov