18

I have found the following code in a project.

What does the !r part mean?

def __repr__(self):
    return f"user={self.user!r}, variant={self.variant!r}"
codeforester
  • 39,467
  • 16
  • 112
  • 140
Nepo Znat
  • 3,000
  • 5
  • 28
  • 49

1 Answers1

23

By default an f-string displays the result of calling str on the values inside the curly braces. Specifying !r displays the result of calling repr instead.

From the docs

The conversion field causes a type coercion before formatting. Normally, the job of formatting a value is done by the format() method of the value itself. However, in some cases it is desirable to force a type to be formatted as a string, overriding its own definition of formatting. By converting the value to a string before calling format(), the normal formatting logic is bypassed.

Three conversion flags are currently supported: '!s' which calls str() on the value, '!r' which calls repr() and '!a' which calls ascii().

Community
  • 1
  • 1
snakecharmerb
  • 47,570
  • 11
  • 100
  • 153
  • 3
    I'll just provide pointers to some documentation: [this SO question](https://stackoverflow.com/questions/44595218/python-repr-for-all-member-variables) and [Python official doc](https://docs.python.org/3/reference/lexical_analysis.html#formatted-string-literals) and [PEP498](https://www.python.org/dev/peps/pep-0498/#s-r-and-a-are-redundant) to have them all! – Léopold Houdin Dec 08 '19 at 10:32