Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

__repr__() returned non-string

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)

like image 843
Smeagol2 Avatar asked Jul 15 '26 14:07

Smeagol2


2 Answers

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.

like image 122
Thomas Orozco Avatar answered Jul 18 '26 04:07

Thomas Orozco


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()))))
like image 42
ptitpoulpe Avatar answered Jul 18 '26 02:07

ptitpoulpe