If you want a stronger syntax, you can use generators / decorators:
from functools import wraps def packed(g): '''a decorator that packs the list data items that is generated by the decorated function ''' @wraps(g) def wrapper(*p, **kw): data = [] for params in g(*p, **kw): fmt = params[0] fields = params[1:] data.append(struct.pack('<'+fmt, *fields)) return ''.join(data) return wrapper @packed def as_binary(self): '''just |yield|s the data items that should be packed by the decorator ''' yield 'I', [2] yield 'II', self.image.size[0], self.image.size[1] yield 'I', len(self.attributes) for attribute in self.attributes: yield 'I', attribute.id yield 'H', attribute.type if attribute.type == 0: yield 'I', attribute.typeEx
It basically uses a generator to implement the “monad,” an abstraction commonly found in functional languages such as Haskell. It separates the generation of some values from the code, which decides to combine these values together. This is a more functional programming approach than pythonic, but I think it improves readability.
sth
source share