bpo-32431: Ensure two bytes objects of zero length compare equal by jonathanunderwood · Pull Request #5021 · python/cpython (original) (raw)

With the current logic in Objects/bytesobject.c in the function bytes_compare_eq can be the case that zero length bytes object object created in an extension module like this:

val = PyBytes_FromStringAndSize (NULL, 20); Py_SIZE(val) = 0;

won't compare equal to b'' because the memory is not initialized, so the first two bytes won't be equal. Nonetheless, the Python interpreter does return b'' for print(repr(val)), so this behaviour is very confusing. To get the correct behaviour, one would have to initialize the memory:

val = PyBytes_FromStringAndSize (NULL, 20); c = PyBytes_AS_STRING (val); c[0] = '\0'; Py_SIZE(val) = 0;

This PR ensures that two zero length byte objects always compare equal irrespecitve of whether the memory has been initialized for either object.

https://bugs.python.org/issue32431