Skip to content

false positive with divmod and overloaded __divmod__ #9835

Closed

Description

from typing import Self, overload

class A:
    @overload
    def __divmod__(self, x: Self, /) -> tuple[Self, Self]: ...
    @overload
    def __divmod__(self, x: int, /) -> tuple[int, int]: ...
    def __divmod__(self, x: Self | int, /) -> tuple[Self, Self] | tuple[int, int]:
        return (self, self) if isinstance(x, A) else (x, x)

reveal_type(divmod(A(), 1))

reports two errors:

No overloads for "divmod" match the provided arguments  (reportCallIssue)
Argument of type "Literal[1]" cannot be assigned to parameter "y" of type "SupportsRDivMod[_T_contra@divmod, _T_co@divmod]" in function "divmod"
  "Literal[1]" is incompatible with protocol "SupportsRDivMod[A, _T_co@divmod]"
    "__rdivmod__" is an incompatible type
      Type "(value: int, /) -> tuple[int, int]" is not assignable to type "(other: _T_contra@SupportsRDivMod, /) -> _T_co@SupportsRDivMod"
        Parameter 1: type "_T_contra@SupportsRDivMod" is incompatible with type "int"
          "A" is not assignable to "int"  (reportArgumentType)

pyright playground


mypy behaves correctly, and reports:

revealed type is "tuple[builtins.int, builtins.int]"

mypy playground

Activity

  1. added
    bug
    on Feb 6, 2025
  2. erictraut commented on Feb 6, 2025

    @erictraut
    Collaborator

    The divmod function is defined as an overloaded function in builtins.pyi:

    @overload
    def divmod(x: SupportsDivMod[_T_contra, _T_co], y: _T_contra, /) -> _T_co: ...
    @overload
    def divmod(x: _T_contra, y: SupportsRDivMod[_T_contra, _T_co], /) -> _T_co: ...

    Here's a version that copies the relevant type definitions out of typeshed into a self-contained sample.

    from typing import Protocol, Self, overload
    
    class SupportsDivMod[T1, T2](Protocol):
        def __divmod__(self, other: T1, /) -> T2: ...
    
    class SupportsRDivMod[T1, T2](Protocol):
        def __rdivmod__(self, other: T1, /) -> T2: ...
    
    @overload
    def divmod[T1, T2](x: SupportsDivMod[T1, T2], y: T1, /) -> T2: ...
    @overload
    def divmod[T1, T2](x: T1, y: SupportsRDivMod[T1, T2], /) -> T2: ...
    
    class A:
        @overload
        def __divmod__(self, x: Self, /) -> tuple[Self, Self]: ...
        @overload
        def __divmod__(self, x: int, /) -> tuple[int, int]: ...
        def __divmod__(self, x: Self | int, /) -> tuple[Self, Self] | tuple[int, int]:
            return (self, self) if isinstance(x, A) else (x, x)
    
    reveal_type(divmod(A(), 1))

    When I run mypy on this code, it generates an error just as pyright does. That seems to imply that mypy is applying some special-case logic for the builtins.divmod, effectively overriding the type definition in typeshed.

    I'm generally very reluctant to add such special-case override logic in pyright. The few times that I've done this in the past, I've come to regret it because it is confusing for users, appears to be inconsistent, and is difficult to maintain — especially when the typeshed definitions inevitably change over time. I might consider breaking this rule if there's significant signal from pyright users that this is an important special case, but I don't recall anyone ever reporting this previously.

    Let's see why the call results in a type error in the first place. This case involves a tricky intersection between overloads, protocol matching, and constraint solving. When performing protocol matching for SupportsDivMod[T1, T2], a type checker must determine which constraints to use for T1 and T2. Since __divmod__ is overloaded in A, it's not clear which overloaded signature should be used for those constraints. It wouldn't work to apply constraints for all overloads; that would inevitably lead to an over-constrained situation and many false positives. Both pyright and mypy use the first assignable overload signature in this situation. Since both overloads in this case are assignable to SupportsDivMod.__divmod__, the first overload is used. This is not ideal, but I don't see a better solution.

    I'll note that this behavior — along with all other constraint-solving behaviors — is not currently covered by the typing spec.

    So, where does that leave us? I think that pyright is doing the right thing here based on the type information it is provided, and its behavior matches that of mypy in the general case.

    It appears that mypy has some special-case hard-coded logic specifically for builtins.divmod, but I'm not inclined to add such logic unless/until there's strong signal from pyright users that this is an important case.

    One workaround that you might consider is to reverse the order of the two A.__divmod__ overloads if you think that an int argument is more common than a Self argument.

  3. jorenham commented on Feb 6, 2025

    @jorenham
    ContributorAuthor

    Since __divmod__ is overloaded in A, it's not clear which overloaded signature should be used for those constraints.

    Both.

    It wouldn't work to apply constraints for all overloads; that would inevitably lead to an over-constrained situation and many false positives.

    I don't see why it would: By interpreting the __divmod__ overloads in terms of a return type that is conditioned on the input types, then the current constraint solver will be able to handle all overloads. That way, the overloads could be written as a single signature, e.g.

    def __divmod__(self, x: Self | int, /) -> (
        case (_, Self) -> tuple[Self, Self]
        case (_, int) tuple[int, int]
    ):
        ...

    I proposed similar idea at https://discuss.python.org/t/make-overload-less-verbose/38803/10, which you might like.

    So, where does that leave us? I think that pyright is doing the right thing here based on the type information it is provided, and its behavior matches that of mypy in the general case.

    Technically, I can understand why this is indeed the case. But in practice, this behavior isn't useful.
    From a user perspective, I think it's more than reasonable to expect that divmod(a, b) will always be accepted if a.__divmod__(b) is accepted.

    One workaround that you might consider is to reverse the order of the two A.__divmod__ overloads if you think that an int argument is more common than a Self argument.

    That would just cause the same problem for the other overload, so I don't consider this a viable workaround.

    The only workaround here is to emulate the divmod runtime behavior by manually calling __divmod__ and __rdivmod__ (or the other way around if the argument types are strict subtypes). But I'm sure you understand that this is just not something I can ask the NumPy and SciPy users to do.

  4. erictraut commented on Feb 6, 2025

    @erictraut
    Collaborator

    I don't think I understand your case notation above. Is this related to your proposal in the link, which involves some form of conditional type mapping? Or do you have something different in mind here?

    Here's what I mean by over-constrained, in case it wasn't clear from my previous post. Let's say that we collect constraints based on both overload signatures. We'd end up with the following four constraints:

    T1 <= Self
    T2 >= tuple[Self, Self]
    T1 <= int
    T2 >= tuple[int, int]
    

    This leads to the following solution. Note that there is no valid solution for T1 because the mutual constraints don't allow for it. That's what I mean by over-constrained.

    T2 = tuple[Self, Self] | tuple[int, int]
    T1 = Never (since A and int don't overlap)
    

    If that doesn't make sense, here's another way of looking at the problem. Rather than using an overload, let's use two separate methods x and y and create a protocol that requires both of these methods. This will force the type checker to consider both the signature of x and y when collecting constraints.

    from typing import Protocol, Self
    
    class XY[T1, T2](Protocol):
        def x(self, other: T1, /) -> T2: ...
        def y(self, other: T1, /) -> T2: ...
    
    class A:
        def x(self, x: Self, /) -> tuple[Self, Self]: ...
        def y(self, x: int, /) -> tuple[int, int]: ...
    
    def func[T1, T2](x: XY[T1, T2]): ...
    
    func(A()) # Type error
  5. jorenham commented on Feb 6, 2025

    @jorenham
    ContributorAuthor

    That makes sense, and I see how this cannot be done with the current constraint solver:
    The overloads are treated as two separate and independent signatures. Their input parameters do no overlap, so they can't be "unified", because Self & int equivs Never.

    The case notation in my example is just way of denoting the case type syntax from https://discuss.python.org/t/make-overload-less-verbose/38803/10. Both describe something that I call a type-mapping. It generalizes a "typevar with constraints", so that e.g. TypeVar("R", A, B) is the type-mapping of A -> A and B -> B. Instead of writing def f(x: R) -> R: ..., with the earlier case syntax it would be

    def f(x: A | B) -> (
        case (A) -> A
        case (B) -> B
    ): ...

    It's not the best syntax, but what I was trying to express, can also be written using the case type syntax from https://discuss.python.org/t/make-overload-less-verbose/38803/10:

    case type R[_: A] = A
    case type R[_: B] = B
    
    def f[T: A | B](x: T) -> R[T]: ...

    By allowing different input- and output-types, you get the type-mapping that I was talking about. With this, the __divmod__ overloads can be rewritten with as follows:

    case type DivmodResult[T: A] = tuple[T, T]
    case type DivmodResult[_: int] = tuple[int, int]
    
    class A:
        def __divmod__[T: Self | int](self, x: T, /) -> DivmodResult[T]: ...

    (the Self is a bit annoying to deal with here, so I'm cheating a bit here and using it as upper bound, and that earlier case syntax was how I tried to avoid this)

    This effecitvely "unifies" the overloads signatures, so that we now have a 1-to-1 correspondence between divmod protocol type parameters, and the input/output types of A.__divmod__.

    Does that make sense?

  6. erictraut commented on Feb 7, 2025

    @erictraut
    Collaborator

    I think I understand what you're saying, although the terminology you're using is a bit confusing to me. I think I'd need to see it spelled out in more detail to fully understand it.

    What you're describing sounds like a facility I added to pyright a couple of years ago that I call "constraint sets". I borrowed the concept from pyre. The mechanism allows for recording and solving multiple independent sets of constraints under certain limited circumstances. It was added to handle ParamSpecs that capture overloaded signatures. However, this mechanism doesn't currently extend to protocol matching. I'll see if it's feasible to extend it in that manner. I have some initial concerns not only about complexity but also about performance. The number of constraint sets could grow very large under common circumstances. The number of constraint sets is equal to the product of all overloads, and protocols can involve many overloads. For example, if a protocol involves 10 methods each with 4 overloads, the number of constraint sets would grow to 4^10, which is over 1 million. Solving one constraint set is expensive at analysis time, and solving a million would take a really long time. So this may prove to be infeasible in practice.

  7. added
    needs investigation
    on Feb 9, 2025
  8. jorenham commented on Feb 9, 2025

    @jorenham
    ContributorAuthor

    I think I understand what you're saying, although the terminology you're using is a bit confusing to me. I think I'd need to see it spelled out in more detail to fully understand it.

    A "type-mapping" could be viewed as overloaded type alias. Its purpose here, is to decouple the type inference (and constraint solving) from the functions/methods.
    An overloaded signature can equivalently be expressed as a single non-overloaded signature, with a single type-mapping as return type. Only one type-mapping is required to do this.
    The type-mapping itself has the same amount of case type statements as the amount of overloads of the signature that it replaces. Each of its case type statements has a direct 1-to-1 correspondence to an overload, and their order also matches.

    The type-mapping return type has an explicit dependence on the types of the input parameters. So e.g. DivmodResult[T] depends on T in the context of A.__divmod__.

    • If x: Self, and therefore T ~ Self, then the first case type of DivmodResult[T] will be used, so that it resolves to tuple[T, T], then tuple[Self, Self].
    • If x: int , and therefore T ~ int, then the second case type will be used, which is tuple[int, int]

    This mechanism for type-mappings should be fully compatible with https://github.com/erictraut/typing/blob/overloads/docs/spec/overload.rst

  9. jorenham commented on Feb 9, 2025

    @jorenham
    ContributorAuthor

    Constraint solving is something I'm not very familiar with. But if I understand correctly, then the constraints that need to be solved, only depend on the input types. Since type-mappings are only used in output positions, they should be able to avoid nasty combinatorial explosions, so that the overloading mechanism can happen after the constraints are solved. This might take a couple of tries, because the overloading mechanism is effectively a refinement on the already-solved constraints (maybe even a special case of a refinement type?).

    Another advantage of the type-mapping approach, is that a single type-mapping can be used for multiple return types. When annotating binary operators that require overloads, there will often be a lot analogous overloads, e.g. in __add__ and __sub__. This might be a way to optimize the algorithm.

  10. erictraut commented on Feb 9, 2025

    @erictraut
    Collaborator

    Constraint solving is one of the more complex parts of a type checker. As my understanding of constraints and constraint solving has evolved over the past five years, I've redesigned and rewritten pyright's constraint solver a couple of times. Each time has been a months-long endeavor. I'm happy with how it's working currently, so I don't plan to do any redesigns at this point. If I'm able to extend the existing mechanism (using "constraint sets") to support protocol matching and this doesn't cause significant performance problems, I will look at doing so. No promises at this point though.

  11. jorenham commented on Feb 9, 2025

    @jorenham
    ContributorAuthor

    I appreciate that! Any way I can help with that?

  12. added
    addressed in next version
    and removed
    needs investigation
    on Feb 9, 2025
  13. erictraut commented on Feb 9, 2025

    @erictraut
    Collaborator

    It looks like the constraint set approach will work, at least for your divmod case.

    I still have concerns about the large number of constraint sets that this could produce, but I already had a (somewhat arbitrary) limit of 1024 constraint sets in the code. If this limit is exceeded, it will fall back to the older behavior. That's preferable to a hang or crash due to memory exhaustion.

    This change will be included in the next release of pyright.

  14. erictraut commented on Feb 12, 2025

    @erictraut
    Collaborator

    This is addressed in pyright 1.1.394.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    addressed in next versionbug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions