typeshed icon indicating copy to clipboard operation
typeshed copied to clipboard

Rewrite `operator` Library with More Specific Annotations

Open George-Ogden opened this issue 1 month ago • 6 comments

More detailed operator annotations could be very useful (see #6448). For example,

def polynomial_derivative(coefficients: Sequence[float]) -> list[float] / list[str]:
    """Compute the first derivative of a polynomial.
    f(x)  =  x³ -4x² -17x + 60
    f'(x) = 3x² -8x  -17
    """
    # polynomial_derivative([1, -4, -17, 60]) -> [3, -8, -17]
    n = len(coefficients)
    powers = reversed(range(1, n))
    return list(map(operator.mul, coefficients, powers))

This used to type check with either return type, but should only work with list[float] now. I haven't done all the annotations as I wanted to test a proof of concept.

George-Ogden avatar Nov 20 '25 15:11 George-Ogden

This seems useful. In fact, I don't know why we're using Any at all here.

srittau avatar Nov 20 '25 17:11 srittau

I ran the mypy primer manually, and there are no changes. For some reason, mypy and GitHub actions don't go well together for larger projects.

George-Ogden avatar Nov 20 '25 17:11 George-Ogden

This is almost ready. I'm unsure whether to delete the fallback overload, as they make the type checking worse. If I remove them, these will no longer be backwards compatible though.

George-Ogden avatar Nov 20 '25 21:11 George-Ogden

I don't know why the CI is failing, but I've had similar issues with mypy in the past.

George-Ogden avatar Nov 20 '25 21:11 George-Ogden

Another thing to note is that for the overloads, the interpreter may run an earlier version (eg __add__ over __radd__) and cause an error when the types don't match. This is different from the type-checker's interpretation.

George-Ogden avatar Nov 20 '25 22:11 George-Ogden

I've managed to reproduce some of the failures locally, and they seem to be due to memory limits. It's crashing on large repos: pandas and homeassistant

George-Ogden avatar Nov 21 '25 09:11 George-Ogden