[Python-Dev] Pre-PEP: The "bytes" object

Neil Schemenauer nas at arctrix.com
Wed Feb 22 22:28:44 CET 2006

On Thu, Feb 16, 2006 at 12:47:22PM -0800, Guido van Rossum wrote:
> BTW, for folks who want to experiment, it's quite simple to create a
> working bytes implementation by inheriting from array.array. Here's a
> quick draft (which only takes str instance arguments):

Here's a more complete prototype.  Also, I checked in the PEP as
#358 after making changes suggested by Guido.


import sys
from array import array
import re
import binascii

class bytes(array):

    __slots__ = []

    def __new__(cls, initialiser=None, encoding=None):
        b = array.__new__(cls, "B")
        if isinstance(initialiser, basestring):
            if isinstance(initialiser, unicode):
                if encoding is None:
                    encoding = sys.getdefaultencoding()
                initialiser = initialiser.encode(encoding)
            initialiser = [ord(c) for c in initialiser]
        elif encoding is not None:
            raise TypeError("explicit encoding invalid for non-string "
        return b

    def fromhex(self, data):
        data = re.sub(r'\s+', '', data)
        return bytes(binascii.unhexlify(data))

    def __str__(self):
        return self.tostring()

    def __repr__(self):
        return "bytes(%r)" % self.tolist()

    def __add__(self, other):
        if isinstance(other, array):
            return bytes(super(bytes, self).__add__(other))
        return NotImplemented

    def __mul__(self, n):
        return bytes(super(bytes, self).__mul__(n))
    __rmul__ = __mul__
    def __getslice__(self, i, j):
        return bytes(super(bytes, self).__getslice__(i, j))

    def hex(self):
        return binascii.hexlify((self.tostring()))

    def decode(self, encoding):
        return self.tostring().decode(encoding)

More information about the Python-Dev mailing list