0

I've written the following two methods in a class:

def __repr__(self):
    return 'REPR: %s' % self.__class__.__name__

def __str__(self):
    return 'STR: %s' % self.__class__.__name__

And to see when they are called:

>>> print t
STR: TPR
>>> t
REPR: TPR
>>> str(t) #obvious
'STR: TPR'
>>> repr(t) #obvious
'REPR: TPR'

Is there a general rule of thumb as to which one is called when, for example, when printing a %s or within a format string, etc. Or is it safe to assume that str is always called if the obj is ever called in some sort of formatted string/unicode place?

Finally, if I ever wanted to "just use one", what would be a better way to do this?

def __repr__(self):
    return __str__(self)

or:

def __str__(self):
    return __repr__(self)

Or does it not matter?

David542
  • 104,438
  • 178
  • 489
  • 842
  • 1
    This seems like a reasonable explanation? https://www.geeksforgeeks.org/str-vs-repr-in-python/#targetText=str()%20is%20used%20for,us%20while%20str%20may%20not. Specifically "The print statement and str() built-in function uses `__str__` to display the string representation of the object while the repr() built-in function uses `__repr__` to display the object." – mayosten Oct 09 '19 at 18:47
  • @mayosten, just note that `print('%r'%obj) ` also uses repr – Demi-Lune Oct 09 '19 at 18:57
  • @Demi-Lune I actually think this gets a bit more complicated than what's listed as a duplicate. For example, doing something like `str([date, date, date])` will use `repr` and not string on all the list elements. – David542 Oct 09 '19 at 19:15
  • There's indeed a remark on this point in the 1st answer of the duplicate. I find their point on "str for human readable " and "repr for unambiguous and `eval`uable" is the key point ... though in the end the developer always gets last decision (for instance, `np.zeros(100)` has an exact repr, but `repr(np.zeros(10000))` shows `array([0., 0., 0., ..., 0., 0., 0.])` ) – Demi-Lune Oct 09 '19 at 21:05

0 Answers0