Issue 24731: Incorrect assert in str_subtype_new (original) (raw)
(Using python 3 terminology) str_subtype_new is the function that creates instances of any subtypes of bytes (ie is called by bytes_new if the requested type is not PyBytes_Type -- looks like this function's name comes from python 2). Its approach is to create a bytes object using the same arguments, and then copy the resulting data into the subclass-instance's memory. It does
tmp = bytes_new(&PyBytes_Type, args, kwds);
[error checking]
assert(PyBytes_CheckExact(tmp));
The problem is that bytes_new can return a subclass of bytes, if the argument provides a bytes method that returns a bytes-subtype. For example
class MyBytes(bytes):
pass
class C(object):
def __bytes__(self):
return MyBytes(b"hello world")
MyBytes(C()) # fails the assert
This doesn't seem to cause any issues other than the failing assert in debug builds; it seems like the assert should just be relaxed from PyBytes_CheckExact to PyBytes_Check since that's enough to guarantee that the upcoming manipulation of the "tmp" variable is going to be valid. Also, this would match how unicode_subtype_new behaves.
This bug also applies to Python 2, since I think the relevant code is the same, though in that case it applies to str instead of bytes.