Created
July 12, 2012 01:10
-
-
Save kurtbrose/3094967 to your computer and use it in GitHub Desktop.
slightly higher level struct
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
| import struct | |
| def make_struct_class(name_format_tuple_list, endian="@"): | |
| names, codes = zip(*name_format_tuple_list) | |
| struct_code = endian + "".join(codes) | |
| serializer = struct.Struct(struct_code) | |
| class StructClass(object): | |
| __slots__ = names | |
| @classmethod | |
| def unpack(cls, string): | |
| self = cls() | |
| for k, v in zip(names, serializer.unpack(string)): | |
| setattr(self, k, v) | |
| return self | |
| def pack(self): | |
| return serializer.pack(*[getattr(self, k) for k in names]) | |
| return StructClass | |
| ''' | |
| >>> A = make_struct_class( [('foo', 'L'), ('bar', 'H')] ) | |
| >>> a = A() | |
| >>> a.foo = 1 | |
| >>> a.bar = 2 | |
| >>> a.pack() | |
| '\x01\x00\x00\x00\x00\x00\x00\x00\x02\x00' | |
| >>> A.unpack(a.pack()).foo | |
| 1 | |
| ''' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment