Skip to content
Tutorials Center
My learning

Topics

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.

Python
repr("hi\n")      # "'hi\\n'"
repr([1, "a"])    # "[1, 'a']"

Try it

Python repr versus str

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.

Python Writing a useful __repr__

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

Python
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)) == x when practical, as the Point example does. When that is impossible, use the angle-bracket form <ClassName ...> that Python itself uses.
  • If a class defines only __repr__, str() and print() 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 why print(["a"]) shows quotes while print("a") does not.
  • In f-strings, {value!r} calls repr(); {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 eval on untrusted text. Parse with ast.literal_eval for plain literals.
  • Dataclasses generate a good __repr__ automatically.
  • Recursive structures (a list containing itself) print [...] instead of looping forever.