How to set a __str__ method for all ctype Structure classes?
- by Reuben Thomas
[Since asking this question, I've found: http://www.cs.unc.edu/~gb/blog/2007/02/11/ctypes-tricks/ which gives a good answer.]
I just wrote a __str__ method for a ctype-generated Structure class 'foo' thus:
def foo_to_str(self):
s = []
for i in foo._fields_:
s.append('{}: {}'.format(i[0], foo.\_\_getattribute__(self, i[0])))
return '\n'.join(s)
foo.\_\_str__ = foo_to_str
But this is a fairly natural way to produce a __str__ method for any Structure class. How can I add this method directly to the Structure class, so that all Structure classes generated by ctypes get it?
(I am using the h2xml and xml2py scripts to auto-generate ctypes code, and this offers no obvious way to change the names of the classes output, so simply subclassing Structure, Union &c. and adding my __str__ method there would involve post-processing the output of xml2py.)