0

I have read and understood the difference between repr and str and noted the difference.

  • repr - unambigous
  • str - readable

What happens is both is used? I wrote a simple class and found that repr is called when both are given.

class test():

    def __repr__(self):
        return 'repr called'

    def __str__(self):
        return 'str called'


x = test()
print x

Now, when I check the implementation of both the classes in Django ValidationError, Im not sure when str will be called as the repr function is already overloaded.

https://docs.djangoproject.com/en/2.0/_modules/django/core/exceptions/#ValidationError

def __str__(self):
    # print 'validationerror str'
    if hasattr(self, 'error_dict'):
        return repr(dict(self))
    return repr(list(self))

def __repr__(self):
    # print 'validationerror repr'
    return 'ValidationError(%s)' % self

How and when the __str__ function will be called?

user1050619
  • 19,822
  • 85
  • 237
  • 413

1 Answers1

1

Basically, __str__() is called for explicit string conversions, i.e. str(x) will call x.__str__(). Some functions like print() will also perform string conversions of their arguments.

The reason your test code calls __repr__() rather than __str__() is that the indentation is off – __str__() isn't actually part of the class, so it's not called. Otherwise print would perform a string conversion, but str(x) falls back to x.__repr__() if __str__() is not definied.

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
  • 1
    Not sure if I understand correctly on the indentation is off stmt..Both repr and str is part of the class. You can see the code in the link that I provided. – user1050619 May 22 '18 at 21:34
  • @user1050619 I think he meant that in your example __str__ has 0 spaces or tabs, while __repr__ has 4 spaces, - it is not a part of your class. But that might be just a sloppy post formatting. – Chiefir May 22 '18 at 22:00
  • Thanks..Yes, it’s a formatting issue, corrected it now. @Sven Marnach – user1050619 May 22 '18 at 23:34
  • @user1050619 But after fixing this, the code won't call `__repr__()` anymore – [it now calls `__str__()`](https://ideone.com/14AT28). – Sven Marnach May 23 '18 at 12:28
  • @Chiefir I would generally have assumed that this is sloppy post formmatting, but the OP clamed that the code called `__repr__()`, and the exact code they posted actually _did_ call `__repr__()`, so I assumed the issue was real in this case. – Sven Marnach May 23 '18 at 12:30