Useful default __repr__ for nested class instances

I have an abstract base class representing an interface. Subclasses of this class are stored as properties of other subclasses of this class.

For instance:

class AbstractBase(object):
    pass

class Child(AbstractBase):
    def __init__(self, cls1, cls2):
        assert isinstance(cls1, AbstractBase)
        assert isinstance(cls2, AbstractBase) # just to show they're instances

        self.cls1 = cls1
        self.cls2 = cls2

The depth and location of the hierarchy cannot be known in advance, but will not be recursive.

What can I put as __repr__on AbstractBase, which will allow me to find the useful properties of each child class in a useful way?

My current approach:

from pprint import pformat

class AbstractBase(object):
    def __repr__(self):
        return self.__class__.__name__ + '\n' \ 
                + pformat({k:v for k,v in self.__dict__.iteritems()
                           if not '__' in k})

For a base class (without properties that are subclasses AbstractBase), this outputs something readable, for example:

MyClass
{'var1': 1,
 'var2': 2}

AbstractBase , , , (, __repr__ ).

- , cls1 cls2 int var:

Child
{'cls1': {
          'var': 1,
         },
 'cls2': {
          'var': 0,
         }
}

, , ( ). ?

+5
2

, :

class AbstractBase(object):
    def __repr__(self, indent=2):
        result = self.__class__.__name__ + '\n'
        for k,v in self.__dict__.iteritems():
            if k.startswith('__'):
                continue
            if isinstance(v, AbstractBase):
                vStr = v.__repr__(indent + 2)
            else:
                vStr = str(v)
            result += ' '*indent + k + ': ' + vStr
        result += '\n'
        return result
+2

, .

. , , , , .

   def __repr__(self, indent=2):
        result = self.__class__.__name__ + '\n'
        items = self.__dict__.items()

        for i,(k,v) in enumerate(items):
            if '__' in k:   
                continue    
            if isinstance(v, AbstractBase):
                vStr = '\n' + ' '*(indent + 2) + v.__repr__(indent + 4)
            elif isinstance(v, collections.Iterable):
                s = str(v)
                bstart = s[0]
                bend = s[-1]

                newIndent = indent + 3
                vStr = '\n' + ' '*(newIndent - 1) + bstart
                for j,item in enumerate(v):
                    if isinstance(item, AbstractBase):
                        if j:
                            vStr += ' '*newIndent
                        vStr += item.__repr__(newIndent + 2)
                    else:    
                        vStr += repr(item)
                    vStr += ',\n'
                vStr += ' '*(newIndent - 1) + bend
            else:              
                vStr = str(v)  
            result += ' '*indent + k + ': ' + vStr

            if i != len(items) - 1:
                result += '\n'

        result = re.sub('\n+', '\n', result)
        return result  
0

All Articles