Home > Software > ToStringBuilder.reflectionToString in Python

ToStringBuilder.reflectionToString in Python

I use Apache Commons ToStringBuilder.reflectionToString whenever I code in Java and thought it would come handy to have a similar construct in Python. What I’ve finally come up with is called make_repr and may be downloaded here along with a simple usage example (it’s all Python license).

So how does it work? Say you have a class like the one below

class Foo(object):
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z

and want to add a nice string representation of it. You could carefully pick the attributes manually and add them to the __repr__ method or you can use make_repr to achieve what follows (I’m assuming make_repr has been saved to a util.py module):

from util import make_repr
 
class Foo(object):
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z
 
    def __repr__(self):
        return make_repr(self)
 
print Foo(1,2,3)

Which will show <Foo at 0x7f2ed9873510 x=[1] y=[2] z=[3]> in the terminal. Callable objects won’t be returned and by the default attributes shown will be sorted alphabetically while any attributes with names starting with a double underscore will be ignored. Another customization option is to_avoid_list – if there’s a class attribute which goes by the name it points to (by default it’s repr_to_avoid, it must be in iterable object, such as a tuple or a list whose elements are names of attributes that must not be returned on the output, like below:

from util import make_repr
 
class Foo(object):
 
    repr_to_avoid = ("x",)
 
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z
 
    def __repr__(self):
        return make_repr(self)
 
print Foo(1,2,3)

Noticed that “x” wasn’t returned on the output?

Well, that’s about it, I hope you like the little tool :-)

Share
Categories: Software Tags: ,
  1. No comments yet.
  1. No trackbacks yet.