Here is a contrived example of how a lot of our classes return binary representations (to be read by C++) of themselves.
def to_binary(self):
'Return the binary representation as a string.'
data = []
# Binary version number.
data.append(struct.pack('<I', [2]))
# Image size.
data.append(struct.pack('<II', *self.image.size))
# Attribute count.
data.append(struct.pack('<I', len(self.attributes)))
# Attributes.
for attribute in self.attributes:
# Id.
data.append(struct.pack('<I', attribute.id))
# Type.
data.append(struct.pack('<H', attribute.type))
# Extra Type.
if attribute.type == 0:
data.append(struct.pack('<I', attribute.typeEx))
return ''.join(data)
What I dislike:
- Every line starts with
data.append(struct.pack(
, distracting from the unique part of the line. - The byte order (
'<'
) is repeated over and over again. - You have to remember to return the boilerplate
''.join(data)
.
What I like:
- The format specifiers appear near the attribute name. E.g., it's easy to see that
self.image.size
is written out as two unsigned ints. - The lines are (mostly) independent. E.g., To remove the Id field from an 'attribute', you don't have to touch more than one line of code.
Is there a more readable/pythonic way to do this?