简体   繁体   中英

fractions.Fraction f-strings as float with __format__

When using a fraction.Fraction in an f-string I would expect to be able to format it as a float . However I get a TypeError :

from fractions import Fraction
f = Fraction(11/10)
f'{f} as float {f:.3f}'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported format string passed to Fraction.__format__

It would seem that the floating point format specs could/should be supported for Fractions .

Interestingly they are for Decimal :

from decimal import Decimal
f = Decimal('1.1')
f'{f} as float {f:.3f}'

Is there a reason this doesn't work for Fraction ?

And yes, I know I could do f'{f} as float {float(f):.3f}' but I'm asking why that's required.

If you don't implement the __format__ method in your class, then you automatically get the default formatter, which just applies the str method. consider

class MyClass:
    """A simple example class"""

    def __str__(self):
        return 'hello world'

If i do

x = MyClass()
y = f"{x}"

then y will have the value "Hello World" . This is because i get the default formatter, which calls my __str__ .

I suspect this is the case with the Fraction class, because when you do help(Fraction.__format__) you get

Help on method_descriptor:

__format__(self, format_spec, /)
    Default object formatter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM