Python Reference ยท Built-in Functions
Python repr() function
Reference for Python repr(): get the unambiguous developer representation of an object, how it differs from str(), and how to define __repr__ for your classes.
The built-in repr() function returns a string that represents an object for developers. The goal is to be unambiguous: for many built-in types the result looks like the Python code that would re-create the value, with quotes around strings and escapes for special characters.
str(), in contrast, aims at readability for end users. For a string they differ visibly: str("hi") is hi, while repr("hi") is 'hi' with the quotes. Containers always use repr() for the items inside them, and the interactive prompt, debuggers and tracebacks do too.
repr("hi\n") # "'hi\\n'" repr([1, "a"]) # "[1, 'a']"
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
repr(object)
| Name | Description |
|---|---|
object |
Any object. |
Return value: a str produced by object.__repr__().
Raises: TypeError if a custom __repr__ returns something that is not a string; any exception your own __repr__ raises.
Usage notes
- Aim for
eval(repr(x)) == xwhen practical, as thePointexample does. When that is impossible, use the angle-bracket form<ClassName ...>that Python itself uses. - If a class defines only
__repr__,str()andprint()fall back to it. If it defines only__str__,repr()still gives the default<__main__.Class object at 0x...>, so always write__repr__first. - Containers show items with
repr(), which is whyprint(["a"])shows quotes whileprint("a")does not. - In f-strings,
{value!r}callsrepr();{value=}prints the name and the repr, useful for quick debugging. - Floats show the shortest string that round-trips:
repr(0.1)is'0.1'. - Non-ASCII characters are kept as they are in
repr.ascii()escapes them if you need a safe, all-ASCII result. - Do not use
evalon untrusted text. Parse withast.literal_evalfor plain literals. - Dataclasses generate a good
__repr__automatically. - Recursive structures (a list containing itself) print
[...]instead of looping forever.