Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
8cf8d31
Add '.f' formatting for Fraction objects
mdickinson Dec 3, 2022
e9db697
Add support for % and F format specifiers
mdickinson Dec 3, 2022
6491b04
Add support for 'z' flag
mdickinson Dec 4, 2022
4551468
Tidy up of business logic
mdickinson Dec 4, 2022
43d34fc
Add support for 'e' presentation type
mdickinson Dec 4, 2022
f8dfcb9
Add support for 'g' presentation type; tidy
mdickinson Dec 4, 2022
6bfbc6c
Tidying
mdickinson Dec 10, 2022
48629b7
Add news entry
mdickinson Dec 10, 2022
3d21af2
Add documentation
mdickinson Dec 10, 2022
c86a57e
Add what's new entry
mdickinson Dec 10, 2022
b521efb
Fix backticks:
mdickinson Dec 10, 2022
aac576e
Fix more missing backticks
mdickinson Dec 10, 2022
b9ee0ff
Fix indentation
mdickinson Dec 10, 2022
1c8b8a9
Wordsmithing for consistency with other method definitions
mdickinson Dec 10, 2022
9dbde3b
Add link to the format specification mini-language
mdickinson Dec 10, 2022
2dd48bb
Fix: not true that thousands separators cannot have an effect for the…
mdickinson Dec 10, 2022
983726f
Fix typo in comment
mdickinson Dec 10, 2022
b7e5129
Tweak docstring and comments for _round_to_exponent
mdickinson Dec 21, 2022
cb5e234
Second pass on docstring and comments for _round_to_figures
mdickinson Dec 21, 2022
907487e
Add tests for the corner case of zero minimum width + alignment
mdickinson Dec 21, 2022
aba35f3
Tests for the case of zero padding _and_ a zero minimum width
mdickinson Dec 21, 2022
fc4d3b5
Cleanup of __format__ method
mdickinson Dec 21, 2022
4ccdf94
Add test cases from original issue and discussion thread
mdickinson Dec 21, 2022
b358b37
Merge branch 'main' into fraction-format
mdickinson Dec 21, 2022
67e020c
Tighten up the regex - extra leading zeros not permitted
mdickinson Dec 21, 2022
e240c70
Merge remote-tracking branch 'mdickinson/fraction-format' into fracti…
mdickinson Dec 21, 2022
111c41f
Add tests for a few more fill character corner cases
mdickinson Dec 21, 2022
d8cc3d6
Merge remote-tracking branch 'upstream/main' into fraction-format
mdickinson Jan 22, 2023
fff3751
Add testcases for no presentation type with an integral fraction
mdickinson Jan 22, 2023
0b8bfa6
Rename the regex to allow for future API expansion
mdickinson Jan 22, 2023
54ed402
Tweak comment
mdickinson Jan 22, 2023
e3a5fd2
Tweak algorithm comments
mdickinson Jan 22, 2023
098d34c
Fix incorrect acceptance of Z instead of z
mdickinson Jan 22, 2023
2c476a2
Use consistent quote style in tests
mdickinson Jan 22, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Add '.f' formatting for Fraction objects
  • Loading branch information
mdickinson committed Dec 3, 2022
commit 8cf8d31ce701235491a0761236cd9f9dcf55146c
99 changes: 99 additions & 0 deletions Lib/fractions.py
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,105 @@ def __str__(self):
else:
return '%s/%s' % (self._numerator, self._denominator)

def __format__(self, format_spec, /):
"""Format this fraction according to the given format specification."""

# Backwards compatiblility with existing formatting.
if not format_spec:
return str(self)

# Pattern matcher for the format spec; only supports "f" so far
FORMAT_SPEC_MATCHER = re.compile(r"""
(?:
(?P<fill>.)?
(?P<align>[<>=^])
)?
(?P<sign>[-+ ]?)
(?P<alt>\#)?
(?P<zeropad>0(?=\d))?
(?P<minimumwidth>\d+)?
(?P<thousands_sep>[,_])?
(?:\.(?P<precision>\d+))?
f
""", re.DOTALL | re.VERBOSE).fullmatch

# Validate and parse the format specifier.
match = FORMAT_SPEC_MATCHER(format_spec)
if match is None:
raise ValueError(
f"Invalid format specifier {format_spec!r} "
f"for object of type {type(self).__name__!r}"
)
elif match["align"] is not None and match["zeropad"] is not None:
# Avoid the temptation to guess.
raise ValueError(
f"Invalid format specifier {format_spec!r} "
f"for object of type {type(self).__name__!r}; "
"can't use explicit alignment when zero-padding"
)
else:
fill = match["fill"] or " "
align = match["align"] or ">"
pos_sign = "" if match["sign"] == "-" else match["sign"]
neg_sign = "-"
alternate_form = bool(match["alt"])
zeropad = bool(match["zeropad"])
minimumwidth = int(match["minimumwidth"] or "0")
thousands_sep = match["thousands_sep"]
precision = int(match["precision"] or "6")

# Get sign and output digits for the target number
negative = self < 0
digits = str(round(abs(self) * 10**precision))

# Assemble the output: before padding, it has the form
# f"{sign}{leading}{trailing}", where `leading` includes thousands
# separators if necessary, and `trailing` includes the decimal
# separator where appropriate.
digits = digits.zfill(precision + 1)
dot_pos = len(digits) - precision
sign = neg_sign if negative else pos_sign
separator = "." if precision or alternate_form else ""
trailing = separator + digits[dot_pos:]
leading = digits[:dot_pos]

# Do zero padding if required.
if zeropad:
min_leading = minimumwidth - len(sign) - len(trailing)
# When adding thousands separators, they'll be added to the
# zero-padded portion too, so we need to compensate.
leading = leading.zfill(
3 * min_leading // 4 + 1 if thousands_sep else min_leading
)

# Insert thousands separators if required.
if thousands_sep:
first_pos = 1 + (len(leading) - 1) % 3
leading = leading[:first_pos] + "".join(
thousands_sep + leading[pos:pos+3]
for pos in range(first_pos, len(leading), 3)
)

after_sign = leading + trailing

# Pad if a minimum width was given and we haven't already zero padded.
if zeropad or minimumwidth is None:
result = sign + after_sign
else:
padding = fill * (minimumwidth - len(sign) - len(after_sign))
if align == ">":
result = padding + sign + after_sign
elif align == "<":
result = sign + after_sign + padding
elif align == "=":
result = sign + padding + after_sign
else:
# Centered, with a leftwards bias when padding length is odd.
assert align == "^"
half = len(padding)//2
result = padding[:half] + sign + after_sign + padding[half:]
return result

def _operator_fallbacks(monomorphic_operator, fallback_operator):
"""Generates forward and reverse operators given a purely-rational
operator and a function from the operator module.
Expand Down
177 changes: 177 additions & 0 deletions Lib/test/test_fractions.py
Original file line number Diff line number Diff line change
Expand Up @@ -830,6 +830,183 @@ def denominator(self):
self.assertEqual(type(f.numerator), myint)
self.assertEqual(type(f.denominator), myint)

def test_format(self):
# Triples (fraction, specification, expected_result)
testcases = [
# Case inherited from object - equivalent to str()
(F(1, 3), '', '1/3'),
(F(-1, 3), '', '-1/3'),
# Simple .f formatting
(F(0, 1), '.2f', '0.00'),
(F(1, 3), '.2f', '0.33'),
(F(2, 3), '.2f', '0.67'),
(F(4, 3), '.2f', '1.33'),
(F(1, 8), '.2f', '0.12'),
(F(3, 8), '.2f', '0.38'),
(F(1, 13), '.2f', '0.08'),
(F(1, 199), '.2f', '0.01'),
(F(1, 200), '.2f', '0.00'),
(F(22, 7), '.5f', '3.14286'),
(F('399024789'), '.2f', '399024789.00'),
# Large precision (more than float can provide)
(F(104348, 33215), '.50f',
'3.14159265392142104470871594159265392142104470871594'),
# Precision defaults to 6 if not given
(F(22, 7), 'f', '3.142857'),
(F(0), 'f', '0.000000'),
(F(-22, 7), 'f', '-3.142857'),
# Round-ties-to-even checks
(F('1.225'), '.2f', '1.22'),
(F('1.2250000001'), '.2f', '1.23'),
(F('1.2349999999'), '.2f', '1.23'),
(F('1.235'), '.2f', '1.24'),
(F('1.245'), '.2f', '1.24'),
(F('1.2450000001'), '.2f', '1.25'),
(F('1.2549999999'), '.2f', '1.25'),
(F('1.255'), '.2f', '1.26'),
(F('-1.225'), '.2f', '-1.22'),
(F('-1.2250000001'), '.2f', '-1.23'),
(F('-1.2349999999'), '.2f', '-1.23'),
(F('-1.235'), '.2f', '-1.24'),
(F('-1.245'), '.2f', '-1.24'),
(F('-1.2450000001'), '.2f', '-1.25'),
(F('-1.2549999999'), '.2f', '-1.25'),
(F('-1.255'), '.2f', '-1.26'),
# Negatives and sign handling
(F(2, 3), '.2f', '0.67'),
(F(2, 3), '-.2f', '0.67'),
(F(2, 3), '+.2f', '+0.67'),
(F(2, 3), ' .2f', ' 0.67'),
(F(-2, 3), '.2f', '-0.67'),
(F(-2, 3), '-.2f', '-0.67'),
(F(-2, 3), '+.2f', '-0.67'),
(F(-2, 3), ' .2f', '-0.67'),
# Formatting to zero places
(F(1, 2), '.0f', '0'),
(F(22, 7), '.0f', '3'),
(F(-22, 7), '.0f', '-3'),
# Formatting to zero places, alternate form
(F(1, 2), '#.0f', '0.'),
(F(22, 7), '#.0f', '3.'),
(F(-22, 7), '#.0f', '-3.'),
# Corner-case: leading zeros are allowed in the precision
(F(2, 3), '.02f', '0.67'),
(F(22, 7), '.000f', '3'),
# Specifying a minimum width
(F(2, 3), '6.2f', ' 0.67'),
(F(12345), '6.2f', '12345.00'),
(F(12345), '12f', '12345.000000'),
# Fill and alignment
(F(2, 3), '>6.2f', ' 0.67'),
(F(2, 3), '<6.2f', '0.67 '),
(F(2, 3), '^3.2f', '0.67'),
(F(2, 3), '^4.2f', '0.67'),
(F(2, 3), '^5.2f', '0.67 '),
(F(2, 3), '^6.2f', ' 0.67 '),
(F(2, 3), '^7.2f', ' 0.67 '),
(F(2, 3), '^8.2f', ' 0.67 '),
# '=' alignment
(F(-2, 3), '=+8.2f', '- 0.67'),
(F(2, 3), '=+8.2f', '+ 0.67'),
# Fill character
(F(-2, 3), 'X>3.2f', '-0.67'),
(F(-2, 3), 'X>7.2f', 'XX-0.67'),
(F(-2, 3), 'X<7.2f', '-0.67XX'),
(F(-2, 3), 'X^7.2f', 'X-0.67X'),
(F(-2, 3), 'X=7.2f', '-XX0.67'),
(F(-2, 3), ' >7.2f', ' -0.67'),
# Corner cases: weird fill characters
(F(-2, 3), '\x00>7.2f', '\x00\x00-0.67'),
(F(-2, 3), '\n>7.2f', '\n\n-0.67'),
(F(-2, 3), '\t>7.2f', '\t\t-0.67'),
# Zero-padding
(F(-2, 3), '07.2f', '-000.67'),
(F(-2, 3), '-07.2f', '-000.67'),
(F(2, 3), '+07.2f', '+000.67'),
(F(2, 3), ' 07.2f', ' 000.67'),
(F(2, 3), '0.2f', '0.67'),
# Thousands separator (only affects portion before the point)
(F(2, 3), ',.2f', '0.67'),
(F(2, 3), ',.7f', '0.6666667'),
(F('123456.789'), ',.2f', '123,456.79'),
(F('1234567'), ',.2f', '1,234,567.00'),
(F('12345678'), ',.2f', '12,345,678.00'),
(F('12345678'), ',f', '12,345,678.000000'),
# Underscore as thousands separator
(F(2, 3), '_.2f', '0.67'),
(F(2, 3), '_.7f', '0.6666667'),
(F('123456.789'), '_.2f', '123_456.79'),
(F('1234567'), '_.2f', '1_234_567.00'),
(F('12345678'), '_.2f', '12_345_678.00'),
# Thousands and zero-padding
(F('1234.5678'), '07,.2f', '1,234.57'),
(F('1234.5678'), '08,.2f', '1,234.57'),
(F('1234.5678'), '09,.2f', '01,234.57'),
(F('1234.5678'), '010,.2f', '001,234.57'),
(F('1234.5678'), '011,.2f', '0,001,234.57'),
(F('1234.5678'), '012,.2f', '0,001,234.57'),
(F('1234.5678'), '013,.2f', '00,001,234.57'),
(F('1234.5678'), '014,.2f', '000,001,234.57'),
(F('1234.5678'), '015,.2f', '0,000,001,234.57'),
(F('1234.5678'), '016,.2f', '0,000,001,234.57'),
(F('-1234.5678'), '07,.2f', '-1,234.57'),
(F('-1234.5678'), '08,.2f', '-1,234.57'),
(F('-1234.5678'), '09,.2f', '-1,234.57'),
(F('-1234.5678'), '010,.2f', '-01,234.57'),
(F('-1234.5678'), '011,.2f', '-001,234.57'),
(F('-1234.5678'), '012,.2f', '-0,001,234.57'),
(F('-1234.5678'), '013,.2f', '-0,001,234.57'),
(F('-1234.5678'), '014,.2f', '-00,001,234.57'),
(F('-1234.5678'), '015,.2f', '-000,001,234.57'),
(F('-1234.5678'), '016,.2f', '-0,000,001,234.57'),
# Corner case: no decimal point
(F('-1234.5678'), '06,.0f', '-1,235'),
(F('-1234.5678'), '07,.0f', '-01,235'),
(F('-1234.5678'), '08,.0f', '-001,235'),
(F('-1234.5678'), '09,.0f', '-0,001,235'),
# Corner-case - zero-padding specified through fill and align
# instead of the zero-pad character - in this case, treat '0' as a
# regular fill character and don't attempt to insert commas into
# the filled portion. This differs from the int and float
# behaviour.
(F('1234.5678'), '0=12,.2f', '00001,234.57'),
# Corner case where it's not clear whether the '0' indicates zero
# padding or gives the minimum width, but there's still an obvious
# answer to give. We want this to work in case the minimum width
# is being inserted programmatically: spec = f'{width}.2f'.
(F('12.34'), '0.2f', '12.34'),
(F('12.34'), 'X>0.2f', '12.34'),
]
for fraction, spec, expected in testcases:
with self.subTest(fraction=fraction, spec=spec):
self.assertEqual(format(fraction, spec), expected)

def test_invalid_formats(self):
fraction = F(2, 3)
with self.assertRaises(TypeError):
format(fraction, None)

invalid_specs = [
"Q6f", # regression test
# illegal to use fill or alignment when zero padding
"X>010f",
"X<010f",
"X^010f",
"X=010f",
"0>010f",
"0<010f",
"0^010f",
"0=010f",
">010f",
"<010f",
"^010f",
"=010f",
]
for spec in invalid_specs:
with self.subTest(spec=spec):
with self.assertRaises(ValueError):
format(fraction, spec)


if __name__ == '__main__':
unittest.main()