Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

f-string representation different than str

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading