print("foo bar")foo bar
repr and str when Printing Objectsprint statement style debugging refers to debugging via format strings or logging
print returns a human readable string
print called with a string displays the string without quotesThere are many ways to modify happens when a variable get’s passed to print
Here all the following are equivalent to the above
str on the variable, then print on the result%s format specifier with the % operatorf"{"foo bar"}"format built-in__format__("s") dunder method__str__ dunder methodfoo bar
foo bar
foo bar
foo bar
foo bar
foo bar
5 and the string "5" have the same output, despite being incompatible types5
5
Is 5 == 5? False
repr stringrepr built-in returns the printable representation on an object
eval it to get the object back'\x07'
'\x07'
repr to ensure type information is conveyed
%r format specifier (% operator) or !r format specifier (format / F-string) is a shorthand for repr5
'5'
Is 5 == '5'?
Is 5 == '5'?
str is called on an argument
__str__ on the argument__str__ falls back to __repr__repreval<__main__.OpaqueClass object at 0x7f4b0efa8590>
repr implementation may be,BetterClass(x=1, y='foo')
repr of x and y to ensure they are also properly representedprint is calling str which resolves to a call on __repr__ due to the missing __str__ method
__str__ method
Human readable: (1, foo)
Representation: BetterClass(x=1, y='foo')
!r on the x and y attributes so they are formatted via str not reprprint returns the str representation of a variable
repr on python built-ins produces the canonical representation of a value
repr strings are typically designed such that eval(repr(obj)) == obj
%s in % operator format strings produces human readable strings via str%r in % operator format strings produces representative strings via repr!r conversion suffix__str__ and __repr__ methods on your classes to control how they are printed when str and repr is called respectively
__str__ method, str will use the __repr__ method__repr__ on an object only provides the type and memory address of an object