◐ Shell
clean mode source ↗

gh-74020: Raise ValueError for negative values converted to unsigned by serhiy-storchaka · Pull Request #121114 · python/cpython

I'm really worried that now, anyone using PyLong_AsUnsignedLong would need to either change how they handle the exception or now be dealing with two different exceptions.

I'm not confident enough to actually just make this change. OverflowError fits in the sense that it's outside of the expected range, but the transition is too hard. I suggested raising DomainError which would inherit from OverflowError and ValueError but code paths with distinct handling of ValueError and OverflowError could be broken.

An easy way to make it work is to introduce a new function that would properly raise what is meant to be raised, and deprecate those functions.

So I'm not -1 as strong as @rhettinger, but I still think it's better to be continue with this, even if it's annoying on our side. We could have some private helpers that would do something like:

try:
	x = asulong(X)
except OverflowError:
	if X < 0:
		raise ValueError
	raise

Or something that can store in addition the fact that something is < 0 or not, like PyLong_AsLongAndOverflow but for ULong instead where we add also a isnegative flag:

int _PyLong_AsUnsignedLong(PyObject *long, int *overflow, int *negative);