Question presented to candidate:
"Python classes can define both __repr__ and __str__. What is the difference between them, when does Python call each one, and if you only had time to write one, which would it be?"
What a strong answer should cover:
__str__is the readable, end-user text (print(x),str(x),f"{x}");__repr__is the unambiguous, developer-facing text (repr(x), the REPL, debuggers, logs).- Containers such as lists and dicts show the
reprof their elements, even when youprintthe container. - The fallback rule: if
__str__is missing,str()uses__repr__; the reverse is not true, so__repr__is the one to write first. - Convention: for simple value types
reprlooks like a constructor call, ideally so thateval(repr(x)) == x; otherwise use the<ClassName ...>style. !rand thef"{x=}"debugging form (Python 3.8+) userepr; both methods must return astr.dataclassesgenerate__repr__for you;reprlib.recursive_reprguards self-referencing objects.
Code / implementation expected: Yes β a small class with both methods, showing print, repr, a list of the objects and an f-string with !r.