How to set a __str__ method for all ctype Structure classes?

Posted by Reuben Thomas on Stack Overflow See other posts from Stack Overflow or by Reuben Thomas
Published on 2011-01-10T00:25:16Z Indexed on 2011/01/13 20:53 UTC
Read the original article Hit count: 246

Filed under:

[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.)

© Stack Overflow or respective owner

Related posts about python