Does struct.pack(f'{len(x)}s', x) do anything at all?

Question:

Consider the following code:

import struct

x = b'example' # can be any bytes object
y = struct.pack(f'{len(x)}s', x)
print(x == y)

If I understand the documentation correctly, the function call will return the binary representation of a struct that has an array of len(x) chars (that contains the contents of x) as its only member. Is there any circumstance under which this will not just be x itself?

Or, to rephrase this question to the C perspective (since I also tagged this question that), does the C standard allow for more than one binary representation of struct MyStruct { char s[MY_SIZE]; };?

I am asking this because Mozilla is instructing me to do just that (Ctrl + F for “Python 3”):

# Encode a message for transmission, given its content.
def encode_message(message_content):
    encoded_content = json.dumps(message_content).encode("utf-8")
    encoded_length = struct.pack('=I', len(encoded_content))
    #  use struct.pack("10s", bytes), to pack a string of the length of 10 characters
    return {'length': encoded_length, 'content': struct.pack(str(len(encoded_content))+"s",encoded_content)}
Asked By: Ground

||

Answers:

It’s entirely pointless. Whoever wrote that example probably didn’t think it through or didn’t quite understand what struct.pack does.

Particularly, even if you had an utterly bizarre platform that would actually pad struct MyStruct { char s[MY_SIZE]; };, the Python struct module still wouldn’t pad that struct.pack call. struct.pack doesn’t add trailing padding (or leading padding, if you had some really weird platform that would do that). Quoting the docs:

Padding is only automatically added between successive structure members. No padding is added at the beginning or the end of the encoded struct.

Answered By: user2357112
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.