gh-67790: Support basic formatting for Fraction by mdickinson · Pull Request #111320 · python/cpython (original) (raw)
PR #100161 added fancy float-style formatting for the Fraction
type, but left us in a state where basic formatting for fractions (alignment, fill, thousands separators) still wasn't supported. For example, we can't currently specify a minimum width for a formatted fraction:
format(Fraction(3, 2), '20') Traceback (most recent call last): File "", line 1, in File "/opt/local/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/fractions.py", line 427, in format raise ValueError( ValueError: Invalid format specifier '20' for object of type 'Fraction'
This PR adds that basic formatting support, aiming for compatibility with int
formatting. The basic formatting is active either with presentation type d
, or with no explicit presentation type. For example, on this branch:
x = Fraction(103993, 33102) f"{x:.<20}" # minimum width, fill and alignment '103993/33102........' f"{x:_}" # thousands separators '103_993/33_102' f"{x:+}" # sign specification '+103993/33102' f"{x:+d}" # explicit 'd' presentation type '+103993/33102' y = Fraction(22) f"{y}" '22' f"{y:#}" # alternate flag '#' forces an explicit denominator '22/1'
All of the above except f"{y}"
currently give ValueError
on main.
Some details:
- Minimum width, fill character, alignment, the sign flag, and thousands separators are supported in the obvious way.
- The zero-fill flag
0
is not supported (though it's still fine to use0
as a fill character in the normal way): it's not 100% clear what the semantics should be (should both the numerator and denominator be padded? Just the numerator?) or what value it would provide, so until someone comes up with valid use-cases that can help inform the semantics, I'm leaving this unsupported. - The alternate flag
#
forces a slash and denominator in the formatted output, even when the output is integer-valued. By default, the slash and denominator are left off for integer-valued fractions.
Pinging @ericvsmith for awareness.
📚 Documentation preview 📚: https://cpython-previews--111320.org.readthedocs.build/