Skip to content

Commit 8af4bd3

Browse files
luantaraschiyouknowone
authored andcommitted
Apply the format spec to a bool instead of dropping it
format_bool answered "True" or "False" for every spec that carries no presentation type, so width, fill, alignment and sign were all discarded: >>> f"{True:>5}" 'True' CPython has no bool.__format__ of its own. It uses int's, where an empty spec on a subclass gives str(self) and everything else formats the integer. The empty spec keeps the spelled out answer, the rest now goes to format_int, which also brings back the errors an integer spec raises. Assisted-by: Claude Code:claude-opus-5
1 parent 3d2ee64 commit 8af4bd3

2 files changed

Lines changed: 98 additions & 7 deletions

File tree

‎crates/common/src/format.rs‎

Lines changed: 64 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -829,6 +829,37 @@ impl FormatSpec {
829829
Ok(self.format_sign_and_align(&AsciiStr::new(&magnitude_str), "", FormatAlign::Right))
830830
}
831831

832+
/// Whether the spec carries nothing at all, which is what `format(value, "")`
833+
/// parses to. Written as a destructure so a new field cannot be forgotten here.
834+
fn is_empty(&self) -> bool {
835+
let Self {
836+
conversion,
837+
fill,
838+
align,
839+
align_specified,
840+
sign,
841+
no_neg_0,
842+
alternate_form,
843+
width,
844+
grouping_option,
845+
precision,
846+
frac_grouping_option,
847+
format_type,
848+
} = self;
849+
conversion.is_none()
850+
&& fill.is_none()
851+
&& align.is_none()
852+
&& !align_specified
853+
&& sign.is_none()
854+
&& !no_neg_0
855+
&& !alternate_form
856+
&& width.is_none()
857+
&& grouping_option.is_none()
858+
&& precision.is_none()
859+
&& frac_grouping_option.is_none()
860+
&& format_type.is_none()
861+
}
862+
832863
pub fn format_bool(&self, input: bool) -> Result<String, FormatSpecError> {
833864
let x = u8::from(input);
834865
match &self.format_type {
@@ -844,13 +875,11 @@ impl FormatSpec {
844875
Some(FormatType::Exponent(_) | FormatType::FixedPoint(_) | FormatType::Percentage) => {
845876
self.format_float(x as f64)
846877
}
847-
None => {
848-
if self.no_neg_0 {
849-
return Err(FormatSpecError::NegativeZeroCoercionNotAllowed("integer"));
850-
}
851-
let first_letter = (input.to_string().as_bytes()[0] as char).to_uppercase();
852-
Ok(first_letter.collect::<String>() + &input.to_string()[1..])
853-
}
878+
// Only the empty spec spells the value out. Everything else without a
879+
// presentation type, a width or an alignment included, formats `bool`
880+
// the way it formats the `int` it is.
881+
None if self.is_empty() => Ok(if input { "True" } else { "False" }.to_owned()),
882+
None => self.format_int(&BigInt::from_u8(x).unwrap()),
854883
Some(format_type) => {
855884
let ch = char::from(format_type);
856885
Err(FormatSpecError::UnknownFormatCode(ch, "bool"))
@@ -1769,6 +1798,34 @@ mod tests {
17691798
assert_eq!(format_bool("%", false), Ok("0.000000%".to_owned()));
17701799
}
17711800

1801+
#[test]
1802+
fn format_bool_without_a_presentation_type() {
1803+
// The bare spec is the only one that spells the value out.
1804+
assert_eq!(format_bool("", true), Ok("True".to_owned()));
1805+
assert_eq!(format_bool("", false), Ok("False".to_owned()));
1806+
1807+
// Anything else formats the integer, the way `int.__format__` would.
1808+
assert_eq!(format_bool("5", true), Ok(" 1".to_owned()));
1809+
assert_eq!(format_bool("<5", true), Ok("1 ".to_owned()));
1810+
assert_eq!(format_bool(">5", false), Ok(" 0".to_owned()));
1811+
assert_eq!(format_bool("^5", true), Ok(" 1 ".to_owned()));
1812+
assert_eq!(format_bool("05", true), Ok("00001".to_owned()));
1813+
assert_eq!(format_bool("+", true), Ok("+1".to_owned()));
1814+
assert_eq!(format_bool(" ", false), Ok(" 0".to_owned()));
1815+
assert_eq!(format_bool(",", true), Ok("1".to_owned()));
1816+
assert_eq!(format_bool("<", true), Ok("1".to_owned()));
1817+
1818+
// And it inherits the integer rules, precision included.
1819+
assert_eq!(
1820+
format_bool(".2", true),
1821+
Err(FormatSpecError::PrecisionNotAllowed)
1822+
);
1823+
assert_eq!(
1824+
format_bool("z", true),
1825+
Err(FormatSpecError::NegativeZeroCoercionNotAllowed("integer"))
1826+
);
1827+
}
1828+
17721829
#[test]
17731830
fn format_string_zero_padding_uses_left_alignment() {
17741831
let spec = FormatSpec::parse("08s").unwrap();

‎extra_tests/snippets/builtin_format.py‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -269,3 +269,37 @@ def test_zero_padding():
269269
assert "{:.3g}".format(1234.5) == "1.23e+03"
270270
assert f"{float('nan'):.10f}" == "nan"
271271
assert f"{float('inf'):.10f}" == "inf"
272+
273+
# bool has no __format__ of its own, so the int rules apply. Only the bare
274+
# spec spells the value out.
275+
assert format(True, "") == "True"
276+
assert format(False, "") == "False"
277+
assert f"{True}" == "True"
278+
assert f"{True:}" == "True"
279+
280+
assert format(True, "5") == " 1"
281+
assert format(True, "<5") == "1 "
282+
assert format(False, ">5") == " 0"
283+
assert format(True, "^5") == " 1 "
284+
assert format(True, "=5") == " 1"
285+
assert format(True, "05") == "00001"
286+
assert format(False, "05") == "00000"
287+
assert format(True, "+") == "+1"
288+
assert format(False, " ") == " 0"
289+
assert format(True, ",") == "1"
290+
assert format(True, "<") == "1"
291+
assert "{:>6}|{:^6}".format(True, False) == " 1| 0 "
292+
293+
# The presentation types were already right, and stay right.
294+
assert format(True, "d") == "1"
295+
assert format(True, "#b") == "0b1"
296+
assert format(False, "x") == "0"
297+
assert format(True, "c") == "\x01"
298+
assert format(True, "e") == "1.000000e+00"
299+
assert format(True, "%") == "100.000000%"
300+
301+
# Precision belongs to no integer spec, bool included.
302+
assert_raises(ValueError, format, True, ".2")
303+
assert_raises(ValueError, format, True, "5.2")
304+
assert_raises(ValueError, format, True, "z")
305+
assert_raises(ValueError, format, True, "s")

0 commit comments

Comments
 (0)