python / python/mypy

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

Open
#19,211 3 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-join-v-union
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

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

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 with the two self-contained reproductions in the issue and run them in the linked mypy playground using mypy 1.15.0 and Python 3.12. Compare the inferred type returned through unwrap with the direct narrowing case; done means both versions type-check without the incompatible return-value error while preserving the declared union.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
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.