!r (a conversion flag) in f-strings.

Celery’s Django docs use a conversion flag within an f-string:

@app.task(bind=True)
def debug_task(self):
    print(f'Request: {self.request!r}')

Apparently, that calls the instance’s __repr__ method instead of the usual __str__ method. What’s __repr__? RealPython.com writes:

The __str__() and __repr__() methods deal with how objects are presented as strings, so you’ll need to make sure you include at least one of those methods in your class definition. If you have to pick one, go with __repr__() because it can be used in place of __str__().

The string returned by __str__() is the informal string representation of an object and should be readable. The string returned by __repr__() is the official representation and should be unambiguous. Calling str() and repr() is preferable to using __str__() and __repr__() directly.

https://realpython.com/python-f-strings/#arbitrary-expressions

Max Brenner writes:

With the return value of repr() it should be possible to recreate our object using eval(). This function takes a string and evaluates it’s content as Python code.

str() – generate output for end user

repr() – generate output for developer

https://shipit.dev/posts/python-str-vs-repr.html

0

Comment via email.