I had always thought that f-strings invoked the __str__ method. That is, f'{x}' is always the same as str(x). However, with this class
class Thing(enum.IntEnum):
A = 0
f'{Thing.A}' is '0' while str(Thing.A) is 'Thing.A'. This example doesn’t work if I use enum.Enum as the base class.
Which functionality do f-strings invoke?
>Solution :
f-strings in Python don’t use __str__ or __repr__. They use __format__.
So to get the same result as f'{Thing.A}', you’d need to call format(Thing.A).
The __format__(...) method allows you to add more formatting features (for example with floats you can do {:.2f} to round the number to two decimals).
If format() hasn’t been defined for a class/object, python will fall back to __str__. That’s why most people think str() is the method used in f-strings.
The docs cover the options you have with __format__ in detail: Link to Documentation