]> git.ipfire.org Git - thirdparty/Python/cpython.git/commit
gh-67790: Support float-style formatting for Fraction instances (#100161)
authorMark Dickinson <dickinsm@gmail.com>
Sun, 22 Jan 2023 18:44:49 +0000 (18:44 +0000)
committerGitHub <noreply@github.com>
Sun, 22 Jan 2023 18:44:49 +0000 (18:44 +0000)
commit3e09f3152e518cdc8779b52943b86812114ce071
treee0305c7963c297e1c36734bd41bd28aa3ee26244
parentb53bad6dd08db78f5b5e2f41bea69c4b657fca13
gh-67790: Support float-style formatting for Fraction instances (#100161)

This PR adds support for float-style formatting for `Fraction` objects: it supports the `"e"`, `"E"`, `"f"`, `"F"`, `"g"`, `"G"` and `"%"` presentation types, and all the various bells and whistles of the formatting mini-language for those presentation types. The behaviour almost exactly matches that of `float`, but the implementation works with the exact `Fraction` value and does not do an intermediate conversion to `float`, and so avoids loss of precision or issues with numbers that are outside the dynamic range of the `float` type.

Note that the `"n"` presentation type is _not_ supported. That support could be added later if people have a need for it.

There's one corner-case where the behaviour differs from that of float: for the `float` type, if explicit alignment is specified with a fill character of `'0'` and alignment type `'='`, then thousands separators (if specified) are inserted into the padding string:

```python
>>> format(3.14, '0=11,.2f')
'0,000,003.14'
```

The exact same effect can be achieved by using the `'0'` flag:

```python
>>> format(3.14, '011,.2f')
'0,000,003.14'
```

For `Fraction`, only the `'0'` flag has the above behaviour with respect to thousands separators: there's no special-casing of the particular `'0='` fill-character/alignment combination. Instead, we treat the fill character `'0'` just like any other:

```python
>>> format(Fraction('3.14'), '0=11,.2f')
'00000003.14'
>>> format(Fraction('3.14'), '011,.2f')
'0,000,003.14'
```

The `Fraction` formatter is also stricter about combining these two things: it's not permitted to use both the `'0'` flag _and_ explicit alignment, on the basis that we should refuse the temptation to guess in the face of ambiguity. `float` is less picky:

```python
>>> format(3.14, '0<011,.2f')
'3.140000000'
>>> format(Fraction('3.14'), '0<011,.2f')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/mdickinson/Repositories/python/cpython/Lib/fractions.py", line 414, in __format__
    raise ValueError(
ValueError: Invalid format specifier '0<011,.2f' for object of type 'Fraction'; can't use explicit alignment when zero-padding
```
Doc/library/fractions.rst
Doc/whatsnew/3.12.rst
Lib/fractions.py
Lib/test/test_fractions.py
Misc/NEWS.d/next/Library/2022-12-10-15-30-17.gh-issue-67790.P9YUZM.rst [new file with mode: 0644]