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:

Pinging @ericvsmith for awareness.


📚 Documentation preview 📚: https://cpython-previews--111320.org.readthedocs.build/