Skip to content

Conversation

@George-Ogden
Copy link

@George-Ogden George-Ogden commented Nov 20, 2025

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 George-Ogden marked this pull request as ready for review November 20, 2025 15:59
@George-Ogden George-Ogden marked this pull request as draft November 20, 2025 15:59
@George-Ogden George-Ogden force-pushed the operator-overhaul branch 2 times, most recently from 1b27d61 to 2a09a2b Compare November 20, 2025 16:47
@srittau
Copy link
Collaborator

srittau commented Nov 20, 2025

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

@George-Ogden
Copy link
Author

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
Copy link
Author

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
Copy link
Author

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

@George-Ogden
Copy link
Author

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.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants