Hacker News new | ask | show | jobs
by jessedhillon 5084 days ago
That's my module. Now, how can I make it better?

You could have those fields know their own sizes, and then you could have Struct subclasses know the size of their instances, so you don't have to call sizeof. E.g.:

    class DataHeader(Struct):
        address = newstruct.long()
        typ =     newstruct.byte()
        tag =     newstruct.short()
        data =    newstruct.byte(length=40) # 40 bytes

    >>> fp = open('mydata', 'rb')
    >>> dh = DataHeader.read(fp)
    # or perhaps: DataHeader.load(fp.read(len(dh)))
    # this way the side-effect of moving fp's current position is more explicit

    >>> fp.close()
    >>> len(dh)
    12345    # or whatever, sum of sizes for long, 41 bytes, and short
1 comments

Additional issues: is a long guaranteed to be 64 bits, or whatever the platform calls long? Is the structure padded (in the same way that the C compiler pads structs)? And, of course, which endianness is used?