fractions: Should we support unicode in width/precision formatting fields?
Open
Nobody has claimed this yet.
stdlib
type-bug
- Dominant language
- Python
- Stars
- 77.2k
- Forks
- 35.9k
- PR merge metrics
- PR metrics pending
Description
Bug report
Bug description:
Currently, specification allows only [0-9] digits. Though, actual implementation permits unicode symbols for float/Decimal's, but not Fraction's:
>>> f"{decimal.Decimal('123'):.١١f}" # arabic 11 in precision
'123.00000000000'
>>> f"{fractions.Fraction('123'):.١١f}"
Traceback (most recent call last):
File "<python-input-9>", line 1, in <module>
f"{fractions.Fraction('123'):.١١f}"
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/sk/src/cpython/Lib/fractions.py", line 600, in __format__
raise ValueError(
...<2 lines>...
)
ValueError: Invalid format specifier '.١١f' for object of type 'Fraction'
>>> f"{float(fractions.Fraction('123')):.١١f}"
'123.00000000000'
Quick tests shows no measurable performance penalty with unicode support:
$ python -m timeit -s 'from fractions import Fraction as F' 'format(F(123), ".11f")'
10000 loops, best of 5: 39.2 usec per loop
$ python -m timeit -s 'from fractions import Fraction as F' 'format(F(123), ".١١f")' # with patch
5000 loops, best of 5: 40.2 usec per loop
a patch
diff --git a/Lib/fractions.py b/Lib/fractions.py
index 063f28478c..b4120b2beb 100644
--- a/Lib/fractions.py
+++ b/Lib/fractions.py
@@ -170,7 +170,7 @@ def _round_to_figures(n, d, figures):
(?P<zeropad>0(?=[0-9]))?
(?P<minimumwidth>0|[1-9][0-9]*)?
(?P<thousands_sep>[,_])?
- (?:\.(?P<precision>0|[1-9][0-9]*))?
+ (?:\.(?P<precision>0|\d*))?
(?P<presentation_type>[eEfFgG%])
""", re.DOTALL | re.VERBOSE).fullmatch
CPython versions tested on:
CPython main branch
Operating systems tested on:
No response
Linked PRs
- gh-140654
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Review the format-specification regex in Lib/fractions.py and the linked PR gh-140654 first. Reproduce the Arabic-digit precision examples for Fraction, Decimal, and float, then compare the result with the documented format specification. Done means Fraction accepts the intended Unicode precision syntax consistently.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- backend
- Issue type
- Bug
- Difficulty
- 1/5
- Estimated time
- Under an hour
- Activity status
- Stale
- Clarity
- Clearly specified
- Newbie friendliness
- 25/100