-1
def serialize_header(header):
    serialized_header = (
        resource_type.ResourceType[header.resource_type].value
        + serialization_method.SerializationMethod[header.serialization_method].value
    ).encode() + struct.pack(
        ">" + "I" * 2 + "H" * 2 + "B" * 2,
        *[
            header.head_revision,
            header.dependency_table_offset,
            header.branch_id,
            header.branch_revision,
            header.compression_flags,
            header.is_compressed,
        ],
    )

    return serialized_header

I have a function that packs data from a list as bytes, is there a way to perform this only for values in the list that aren't None? For example, header.head_revision may be None. Is there a way to do the same thing I'm doing, but don't pack None values?

JZQAr9kW
  • 13
  • 2
  • This reminds me of [this answer](https://stackoverflow.com/a/52494213/2550406). Although it is decidedly a different question, the answer might be similar. Basically: You already have a list there. All you need is saying `*[v for v in [ ... ] if v is not None]`. But ... how will you know which one was none, when you later try to unpack it again? – lucidbrot May 14 '22 at 15:36
  • Welcome to Stack Overflow. "For example, header.head_revision may be None." Okay, and *what should happen* in this case? How do you want to represent that fact in the packed data? If you just want to skip it entirely, then how do you intend to make sense of the unpacked data later? For example, if the data is only 10 bytes long instead of the full 14, then how do you know which of the `"I"` sized fields was left out? Or maybe it was both of the `"H"` fields? Or one of the `"H"` fields and both of the `"B"` fields? – Karl Knechtel May 15 '22 at 06:37
  • If something is None it should be skipped entirely, which values exist and don't exist are based off the head_revision which is never None, the unpacker just sets values that don't exist in the binary data to None, and when I pack them I want those values to not exist at all in the binary data. – JZQAr9kW May 15 '22 at 06:42

0 Answers0