Skip to content

Custom protocols for builtin numbers #2886

@v--

Description

@v--

Summary

For working with abstract algebraic structures, I found it useful to define the following protocol (with some simplification):

from typing import Protocol, Self


class ISemiring(Protocol):
    def __add__(self, other: Self, /) -> Self:
        ...

    def __mul__(self, other: Self, /) -> Self:
        ...

Consider the following simple function:

def frobnicate(x: ISemiring) -> None:
    ...


def wrapper_int(x: int) -> None:
    frobnicate(x)  # ty agrees that `int` is a subtype


def wrapper_float(x: float) -> None:
    frobnicate(x)  # ty disagrees that `float` is a subtype

See this playground page. I do not have further clues about what goes wrong (except that replacing Self with float works). complex values have the same problem. Sorry if I am missing something obvious.

Both of the above functions are fine with mypy 1.19.1 and pyrefly 0.53.0 (mypy doesn't even need the trailing slashes in the argument lists in the protocol).

Version

ty 0.0.18

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions