[Python-3000] tp_bytes and __bytes__ magic method

Guido van Rossum guido at python.org
Thu Aug 9 02:00:44 CEST 2007


> On Thursday 09 August 2007 00:54:47 Guido van Rossum wrote:
> > On 8/8/07, Christian Heimes <lists at cheimes.de> wrote:
> > > Victor Stinner just made a good point at #python. The py3k has no magic
> > > method and type slot for bytes (...)
> > > I can think of a bunch of use cases for a magic method.
> >
> > Such as?

On 8/8/07, Victor Stinner <victor.stinner at haypocalc.com> wrote:
> I'm writting on email module and I guess that some __str__ methods should
> return bytes instead of str (and so should be renamed to __bytes__). Maybe
> the one of Message class (Lib/email/message.py).

On 8/8/07, Christian Heimes <lists at cheimes.de> wrote:
> The __bytes__ method could be used to implement a byte representation of
> an arbitrary object. The byte representation can then be used to submit
> the object over wire or dump it into a file. In Python 2.x I could
> overwrite __str__ to send an object over a socket but in Python 3k str()
> returns a unicode object that can't be transmitted over sockets. Sockets
> support bytes only.

This could just as well be done using a method on that specific
object. I don't think having to write x.as_bytes() is worse than
bytes(x), *unless* there are contexts where it's important to convert
something to bytes without knowing what kind of thing it is. For
str(), such a context exists: print(). For bytes(), I'm not so sure.
The use cases given here seem to be either very specific to a certain
class, or could be solved using other generic APIs like pickling.

-- 
--Guido van Rossum (home page: http://www.python.org/~guido/)


More information about the Python-3000 mailing list