You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
false positive with divmod and overloaded __divmod__ #9835
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)
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.
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]
):
...
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.
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:
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.
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.
case type R[_: A] =Acase type R[_: B] =Bdeff[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]
classA:
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__.
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.
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]
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.
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.
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.
Activity
erictraut commentedon Feb 6, 2025
The
divmodfunction is defined as an overloaded function inbuiltins.pyi:Here's a version that copies the relevant type definitions out of typeshed into a self-contained sample.
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 forT1andT2. Since__divmod__is overloaded inA, 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 toSupportsDivMod.__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 anintargument is more common than aSelfargument.jorenham commentedon Feb 6, 2025
Both.
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.I proposed similar idea at https://discuss.python.org/t/make-overload-less-verbose/38803/10, which you might like.
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 ifa.__divmod__(b)is accepted.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
divmodruntime 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.erictraut commentedon Feb 6, 2025
I don't think I understand your
casenotation 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:
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.
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
xandyand create a protocol that requires both of these methods. This will force the type checker to consider both the signature ofxandywhen collecting constraints.jorenham commentedon Feb 6, 2025
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 & intequivsNever.The
casenotation in my example is just way of denoting thecase typesyntax 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 ofA -> AandB -> B. Instead of writingdef f(x: R) -> R: ..., with the earliercasesyntax it would beIt's not the best syntax, but what I was trying to express, can also be written using the
case typesyntax from https://discuss.python.org/t/make-overload-less-verbose/38803/10: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:(the
Selfis a bit annoying to deal with here, so I'm cheating a bit here and using it as upper bound, and that earliercasesyntax 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?
erictraut commentedon Feb 7, 2025
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.
jorenham commentedon Feb 9, 2025
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 typestatements as the amount of overloads of the signature that it replaces. Each of itscase typestatements 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 onTin the context ofA.__divmod__.x: Self, and thereforeT ~ Self, then the firstcase typeofDivmodResult[T]will be used, so that it resolves totuple[T, T], thentuple[Self, Self].x: int, and thereforeT ~ int, then the secondcase typewill be used, which istuple[int, int]This mechanism for type-mappings should be fully compatible with https://github.com/erictraut/typing/blob/overloads/docs/spec/overload.rst
jorenham commentedon Feb 9, 2025
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.erictraut commentedon Feb 9, 2025
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.
jorenham commentedon Feb 9, 2025
I appreciate that! Any way I can help with that?
Added support for tracking multiple constraint sets when performing p…
Added support for tracking multiple constraint sets when performing p…
erictraut commentedon Feb 9, 2025
It looks like the constraint set approach will work, at least for your
divmodcase.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.
erictraut commentedon Feb 12, 2025
This is addressed in pyright 1.1.394.
Revert "Added support for tracking multiple constraint sets when perf…
Revert "Added support for tracking multiple constraint sets when perf…
Merge branch 'main' into issue-10625