6

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)

user1509923
  • 193
  • 1
  • 3
  • 13

3 Answers3

12

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.

Thomas Orozco
  • 53,284
  • 11
  • 113
  • 116
2

your __repr__(self) method must return a string:

def __repr__ (self): 
 return "\n".join("\t".join (row) for row in zip(*([ky]+map(str,val) for ky,val in (self.slovar.items()))))
glglgl
  • 89,107
  • 13
  • 149
  • 217
ptitpoulpe
  • 684
  • 4
  • 17
1

You could do it like this:

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

This way it remains readable and compact.

glglgl
  • 89,107
  • 13
  • 149
  • 217