1

I guess this is best explained by code and comments:

import struct

class binary_buffer(str):
    def __init__(self, msg=""):
        self = msg
    def write_ubyte(self, ubyte):
        self += struct.pack("=B", ubyte)
        return len(self)

Output
>> bb = binary_buffer()
>> bb # Buffer starts out empty, as it should
''
>> bb.write_ubyte(200)
1   # We can see that we've successfully written one byte to the buffer
>> bb
''  # Huh? We just wrote something, but where has it gone?

1 Answer 1

4

strs are immutable. Therefore,

self += struct.pack("=B", ubyte)

is evaluated as

self = self + struct.pack("=B", ubyte)

This assigns a new value to the name self, but self is just a name like any other. As soon as the method exits, the name (and the associated object) are forgotten.

You want a bytearray:

>>> bb = bytearray()
>>> bb.append(200)
>>> bb
bytearray(b'\xc8')
Sign up to request clarification or add additional context in comments.

5 Comments

I'd say that in general, assigning to "self" is wrong. At least I can't come up with a legitimate use for this.
@doomster: Why is that? And how else would you do it?
@TahitiPetey Because you're just binding something to the name self, which is usually your current object. To change the current object, assign to one of its properties, or, equivalently, call one of its methods.
@phihag: So when I simply use bb, what method is it invoking to return the bytearray? Is not using self? I would like to be able to pass the binary_buffer object into a socket.sendto() method as the message. Is there a more 'pythonic' way of doing this?
@TahitiPetey bytearray.append(x) is (approximately) implemented as self._bytes += x. You can pass in a bytearray object to sendto, but you can always create an immutable bytes object from it with bytes(bb).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.