-
-
Save mwhooker/3114130 to your computer and use it in GitHub Desktop.
named structs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
from collections import namedtuple | |
from struct import Struct | |
class NamedStruct(Struct): | |
def __init__(self, name, fields, byteorder=None): | |
fmt = (byteorder or '') + ''.join(field[0] for field in fields) | |
super(NamedStruct, self).__init__(fmt) | |
self.namedtuple = namedtuple(name, (field[1] for field in fields)) | |
def pack(self, *args, **kwargs): | |
arguments = self.namedtuple(*args, **kwargs) | |
return super(NamedStruct, self).pack(*arguments) | |
def pack_into(self, buf, offset, *args, **kwargs): | |
arguments = self.namedtuple(*args, **kwargs) | |
return super(NamedStruct, self).pack_into(buf, offset, *arguments) | |
def unpack(self, *args, **kwargs): | |
unpacked = super(NamedStruct, self).unpack(*args, **kwargs) | |
return self.namedtuple(*unpacked) | |
def unpack_from(self, *args, **kwargs): | |
unpacked = super(NamedStruct, self).unpack_from(*args, **kwargs) | |
return self.namedtuple(*unpacked) | |
if __name__ == '__main__': | |
ns = NamedStruct('Header', fields=( | |
('b', 'length'), | |
)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment