__repr__() returned non-string

user1509923 picture user1509923 · Dec 5, 2012 · Viewed 17.6k times · Source

So I have a class method with which I would like to draw out the dictionary and it's values:

 def __repr__ (self): 
        for row in zip(*([ky]+map(str,val) for ky,val in (self.slovar.items()))):

           print"\t".join (row)

If it's like this, I get a desired output:

>>> test
n   n1  n2
1   a   2.3
2   b   2.1
3   d   2.5

Traceback (most recent call last):
  File "<pyshell#521>", line 1, in <module>
    test
TypeError: __repr__ returned non-string (type NoneType)

but also a Traceback error.

If I return the value instead of printing it out, I only get this:

>>> test
n   n1  n2

It works fine if I make a custom method not the default 'system' one... (and I need it to be default)

Answer

Thomas Orozco picture Thomas Orozco · Dec 5, 2012

Your __repr__ method is using print to output information, but has no return statement, so it is effectively returning None, which is not a string.


What you could do is:

def __repr__ (self): 
    parts = []
    for row in zip(*([ky]+map(str,val) for ky,val in (self.slovar.items()))):
       parts.append("\t".join (row))
    return '\n'.join(parts)

You might also want to have a look at the pprint module.