Skip to content

mypy reports an error with a function with generic argument. #18544

Closed as not planned
@s17b2-voroneckij

Description

@s17b2-voroneckij

Bug Report

For a function that accepts objects of A | B | C type, mypy is not correctly inferring types for function calls from that object.

To Reproduce
https://mypy-play.net/?mypy=latest&python=3.12&gist=a090296a66d822acabcb0e92e53f5871

from typing import Self, reveal_type, Protocol


class A:
    def dup(self) -> list[Self]:
        return [self, self]


class B:
    def dup(self) -> list[Self]:
        return [self, self]


class C:
    def dup(self) -> list[Self]:
        return [self, self]


class HasDup(Protocol):
    def dup(self) -> list[Self]: ...


def process[T: A | B | C](elem: T) -> list[T]:
    reveal_type(elem.dup)
    duplicated: list[T] = elem.dup()
    return duplicated


process(A())
process(B())
process(C())

Expected Behavior
No error to be reported

Actual Behavior
main.py:24: note: Revealed type is "Union[def () -> builtins.list[main.A], def () -> builtins.list[main.B], def () -> builtins.list[main.C]]"
main.py:25: error: Incompatible types in assignment (expression has type "list[A] | list[B] | list[C]", variable has type "list[T]") [assignment]
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: 1.14.1
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3,12

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions