[Python-ideas] Allow __bytes__ to return NotImplemented
Émanuel Barry
vgr255 at live.ca
Mon Jun 6 14:36:53 EDT 2016
> From: Guido van Rossum
> Sent: Monday, June 06, 2016 2:19 PM
> To: Émanuel Barry
> Cc: Python-Ideas
> Subject: Re: [Python-ideas] Allow __bytes__ to return NotImplemented
>
> 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.
> 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.
Thanks for the reply,
-Emanuel
More information about the Python-ideas
mailing list