Skip to content

"is not assignable to upper bound" when using Protocol #2421

Description

@MarcoGorelli

Describe the Bug

The following example type checks fine with mypy/pyright, but raises

ERROR `MySeries` is not assignable to upper bound `NativeSeries` of type variable `T` [bad-specialization]
  --> t.py:15:17
   |
15 | def to_foo() -> Foo[MySeries]:
   |                 ^^^^^^^^^^^^^
   |
  `MySeries.filter` has type `BoundMethod[MySeries, (self: MySeries, _predicate: Iterable[bool]) -> MySeries]`, which is not assignable to `BoundMethod[MySeries, (self: MySeries, *args: Any, **kwargs: Any) -> Any]`, the type of `NativeSeries.filter`

for pyrefly

from typing import Generic, Sized, Iterable, Any, TypeVar, Protocol, Self

class NativeSeries(Protocol):
    def filter(self, *args: Any, **kwargs: Any) -> Any: ...

class MySeries:
    def filter(self, _predicate: Iterable[bool]) -> Self:
        return self

T = TypeVar('T', bound=NativeSeries)

class Foo(Generic[T]):
    ...

def to_foo() -> Foo[MySeries]:
    ...

spotted in narwhals

Sandbox Link

https://pyrefly.org/sandbox/?project=N4IgZglgNgpgziAXKOBDAdgEwEYHsAeAdAA4CeS4ATrgLYAEALqcROgOZ0Q3G6UN0BxGOhiUIAYwA0dAMoQAXjEzSAkg1GpssaQEF0paQBVmMAGqpK0gArUGucbijSZMKGAA66T%2BKio4cOgA5VAYIADcYFzF4AAobXDsHKABKRE86DLpMGDA6SCh1Shi4VzBpACoLNjhEOj0DOnLygGsAdyqauv1kugBaAD4u0lrCUc9vX386AFlSKIh4NPRMrJy86ELi0ukAfWJKJQkQmFq1DS0YAG08RwBdHoHZUqWVlYOGAFdKZZK3cfRDHQALx0YzEMwWGIAckMUOkeA%2BWCBwVCEXm8GS-x8fgCADFcLgYkIRGJxJdDPcXplRoR-tlcnYdmACTEHoN8bhLrN0XBblSMjT-iBJCAPqEoHASORECAAMR0ACq4ogTDyiPEoVw6DgdLWzMoNBCO3QHxo2FEMXwtVYDDZdDgDEo-Lo7y%2Byw8IECpvNTrowHwAF93CBPMKQGQDmAoKRCHYaFAKPKrKRI9H7RgcAQ6A50JA2F8QhAtbT0PKXDA6AALBgMYg1AD09YjOWjhF4bHrwnrmHscHrObzBc16HreV4dFQYVQ0E0sGzWsHlELWrouGIw8lnjIDErWt6EUocCLyxBwYAzIQAIwAJmDoYDItQGvCMFx0BgFDQWDwRDIIADQA

(Only applicable for extension issues) IDE Information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    needs-discussionAn issue where it's not clear whether there is a bug or we are behaving as expected.

    Type

    Fields

    No fields configured for Bug.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions