[Python-ideas] Allow __bytes__ to return NotImplemented

Guido van Rossum guido at python.org
Mon Jun 6 14:18:45 EDT 2016


Can't you just raise an exception when __bytes__() is called if the
underlying representation uses str?

Returning NotImplemented is not the right thing here -- that's not
supposed to make it into user code, it's only meant to be used when
there's a binary operation, to give the other argument a chance at
providing an implementation. (And if they both return NotImplemented,
Python will always turn that into a TypeError or a default answer.)
But for unary operators like bytes() there's no such thing, and the
NotImplemented would leak into user code, where it can do more damage
than good.

On Mon, Jun 6, 2016 at 10:05 AM, Émanuel Barry <vgr255 at live.ca> wrote:
> 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
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/



-- 
--Guido van Rossum (python.org/~guido)


More information about the Python-ideas mailing list