Skip to main content
  1. About
  2. For Teams
Asked
Viewed 8k times
25

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}"
0

1 Answer 1

30

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().

Sign up to request clarification or add additional context in comments.

1 Comment

I'll just provide pointers to some documentation: this SO question and Python official doc and PEP498 to have them all!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.

Morty Proxy This is a proxified and sanitized view of the page, visit original site.