repr()
The debug representation — unambiguous, quoted, and often eval-able. The str/repr split lets one object display two ways.
Demo
repr wraps strings in quotes and escapes special characters — a newline becomes "\n" in the output, a tab becomes "\t", and internal quotes get escaped or the outer quote choice switches. That is by design: the output should be a valid Python literal you could paste back into code. str() would show the raw value; repr() shows how to type the same value.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| x | Any | yes | Any value. Python calls __repr__() on it — every object has one, so repr never raises AttributeError on missing method. |
Return value
str — The "official" string representation of the object, produced by calling __repr__(). For built-in types this is typically a valid Python literal that would recreate the object when passed to eval(). Never falls back to __str__.
Common patterns
logger.debug(f"received user={user!r} action={action!r}")
class Point: def __repr__(self): return f"Point({self.x!r}, {self.y!r})"
print(repr("say "hi"")) # "say "hi"" or 'say "hi"'
Examples
Pitfalls
log.info(f"got {value}") # value is "5\t" # logs: got 5<TAB>
log.info(f"got {value!r}")
eval(repr(user))
# repr is for HUMANS to read, not for machines to parseclass Point: pass repr(Point())
class Point: def __repr__(self): return f"Point(...)"
log.debug(repr(giant_state))
log.debug(repr(giant_state)[:200] + "...")
When to use
- Debug / diagnostic output — logs, error messages, assertions
- f-string with !r spec for logging user-provided values
- Round-trippable data output for simple built-in types
- Defining __repr__ on your own classes
- User-facing text → str is the correct tool
- JSON output → json.dumps
- Parsing objects — never eval a repr from untrusted input
- Very large collections — truncate first
Notes
FAQ
str is for humans — clean, presentable, may lose information. repr is for debugging — unambiguous, includes quotes for strings and escapes for special characters. For simple built-in types they usually differ; for containers repr shows how you would type it, str is essentially the same as repr.