[Tutor] __str__ Vs __repr__

Cameron Simpson cs at cskk.id.au
Tue Nov 30 15:43:09 EST 2021


On 30Nov2021 22:35, Manprit Singh <manpritsinghece at gmail.com> wrote:
>After assigning a value to a variable, Lets say variable is a, and the
>value assigned to it is 5,
>On an interactive shell after writing a and then hitting Enter key, it
>prints the value of a, that is 5, This happens due to __str__ or __repr__?

__repr__, because that generally provides greater detail. Ideally it 
provides text which you could run as a Python expression to get the 
value.

__str__ is intended for "normal output", whatever that means :-( The 
print() function calls __str__ on every object it prints. So when you 
go:

    print('foo')

you get a bare:

    foo

without any quotes. Generally an object's __str__ should be concise and 
not have much punctuation in it. It should make sense when the reader 
already knows what type of thing is being printed.

>What should I use(__str__ or  __repr__) if I want something to be printed
>when I print an object of a user defined class ?

That depends entirely on context, unfortunately. It isn't "what version 
should I print?" but "what version does the user want?"

If you're talking to an end user (instead of you, the programmer, at the 
interactive prompt) you probably want __str__ (because print() will do 
that for you automatically), and a better question is instead: what 
should __str__ return? Something concise and readable. __repr__ is for 
the programmer doing debugging.

Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Tutor mailing list