On Mon, Jun 6, 2016 at 11:36 AM, Émanuel Barry
From: Guido van Rossum Can't you just raise an exception when __bytes__() is called if the underlying representation uses str?
Sure (that's what I'm doing right now), but my intention was that returning NotImplemented would make bytes() fall back to the default behaviour. But for my use case, it makes no difference as an error is raised either way, just a different one.
To invoke the default behavior just return super().__bytes().
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.
My understanding was that returning NotImplemented would tell the caller (here, bytes()) "I can't do that, figure it out yourself" like binary operations do, which would eventually become an error. It made sense to me at the time, but now I realize that it doesn't make sense if there's only one argument, so I'll raise the error myself.
Right. NotImplemented is frequently misunderstood (and it doesn't help that there's also a completely unrelated exception NotImplementedError). If you want to contribute some docs about this we'd be delighted! (bugs.python.org) -- --Guido van Rossum (python.org/~guido)