[Python-ideas] Allow __bytes__ to return NotImplemented

Émanuel Barry vgr255 at live.ca
Mon Jun 6 13:05:02 EDT 2016


I'm currently writing a class that can take either a str of bytes object,
and is meant to work with either type. For my purpose, it makes sense to
return the underlying bytes object when calling bytes() on it. However,
defining __bytes__ on the class means that I also have to return bytes even
if the underlying object is a str. The obvious way to fix this is to define
two different classes, one which handles str and one which handles bytes.
However, I was wondering if returning NotImplemented from __bytes__ would be
a viable alternative.

I'm not sure if there'd be any performance hit (there is probably some
optimized C code that simply checks for the existence of __bytes__ in the
namespace without calling it), but hopefully there aren't.

Another alternative would be to define object.__bytes__, which one can call
to fall back to the default behaviour.

While I'm at it, maybe other methods could use that, too (thinking mainly of
__int__, __float__, __abs__, __complex__, __round__, __index__, and maybe
__len__ and __iter__).

Thoughts? Is it reasonable to define a single class that can work with both
str and bytes, or should I fix my code?

-Emanuel


More information about the Python-ideas mailing list