FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

Apply the format spec to a bool instead of dropping it by luantaraschi · Pull Request #8566 · RustPython/RustPython · GitHub

Apply the format spec to a bool instead of dropping it - #8566

Merged
youknowone merged 1 commit into
RustPython:mainfrom
luantaraschi:fix/bool-format-spec
Aug 22, 2026
Merged

Apply the format spec to a bool instead of dropping it#8566
youknowone merged 1 commit into
RustPython:mainfrom
luantaraschi:fix/bool-format-spec

Conversation

luantaraschi commented Aug 21, 2026
edited by coderabbitai Bot
Loading

Copy link
Copy Markdown
Contributor

Summary

A bool ignores every format spec that does not name a presentation type:

>>> f"{True:>5}"
'True'                            # CPython: '    1'
>>> "{:>6}|{:^6}".format(True, False)
'True|False'                      # CPython: '     1|  0   '
>>> format(True, "05")
'True'                            # CPython: '00001'
>>> format(True, ".2")
'True'                            # CPython: ValueError: Precision not allowed in integer format specifier

Width, fill, alignment, sign and the thousands separator are all dropped, and a spec that an integer would reject is accepted quietly. Lining a boolean column up in a table is the case that runs into this, since that spec has no type letter in it.

format(True, "d") and the rest of the presentation types were already right, which is why this only shows up on the specs that leave the letter out.

FormatSpec::format_bool has a None arm for "no presentation type" that returns the spelled out name whatever else the spec holds. CPython does not give bool a __format__ at all:

>>> "__format__" in vars(bool)
False

It inherits int.__format__, and the rule there is the one already written in PyInt::__format__ in this tree: an empty spec on a subclass gives str(self), anything else formats the integer. So the empty spec keeps the old answer and every other spec goes to format_int, which is also what restores Precision not allowed in integer format specifier and the z rejection.

is_empty is written as a destructure of Self rather than a chain of self.field, so that adding a field to FormatSpec later fails to compile here instead of silently making an empty spec look non-empty.

The literal "True" / "False" replaces a round trip through to_string() plus to_uppercase() on the first byte, in the arm that was being rewritten anyway.

Test Plan

Built in a Debian container on rustc 1.98.0.

  • crates/common/src/format.rs gains format_bool_without_a_presentation_type, next to the existing format_bool_basic. Without the change it fails with left: Ok("True") against right: Ok(" 1").
  • extra_tests/snippets/builtin_format.py gains the same ground at the Python level, including the four specs that have to raise. Without the change it stops at assert format(True, "5") == " 1".
  • pytest test_snippets.py -k builtin_format, both legs green, so the file also holds under CPython 3.14.7.
  • -m test test_format, -m test test_bool and -m test test_types on the release build: 18, 31 and 129 tests, all SUCCESS.
  • cargo clippy with the flags CI uses, clean, and cargo fmt --check clean. ruff format --check and ruff check --select I clean on the snippet.
  • cargo test --workspace --exclude rustpython_wasm --exclude rustpython-venvlauncher --exclude rustpython-capi: no failures.

The three clippy jobs and the WASM check are red for the reason in #8564, unrelated to this change.

Summary by CodeRabbit

  • New Features

    • Improved boolean formatting with integer-style alignment, width, zero-padding, signs, and grouping.
    • Added clear True/False output for empty formatting specifications.
  • Bug Fixes

    • Boolean formatting now reports errors for unsupported precision and string-style specifications.
    • Missing presentation types correctly follow integer formatting behavior.
    • Unknown conversion specifiers now produce a clear ValueError message.

coderabbitai Bot commented Aug 21, 2026
edited
Loading

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info ⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro Plus

Run ID: dcc84219-ea1d-4c5e-ba8f-aa817942d469

📥 Commits

Reviewing files that changed from the base of the PR and between c344c34 and 8af4bd3.

📒 Files selected for processing (1)
  • extra_tests/snippets/builtin_format.py

Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.


📝 Walkthrough

Walkthrough

Boolean formatting now spells values only for empty specifications. Non-empty specifications use integer formatting rules, including width, alignment, signs, grouping, presentation types, and related errors. Rust and Python tests cover these behaviors.

Changes

Boolean formatting

Layer / File(s) Summary
Format specification and boolean formatting
crates/common/src/format.rs, extra_tests/snippets/builtin_format.py
FormatSpec::is_empty identifies empty specifications. Boolean formatting uses True/False for empty specifications and integer formatting for non-empty specifications. Tests cover alignment, width, padding, signs, grouping, presentation types, precision, unsupported specifications, and unknown conversion specifiers.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Merge Risk: ⚪ Minimal · up to 8af4b

This change makes boolean formatting follow integer formatting rules for width, alignment, padding, signs, separators, and invalid precision specs, with targeted coverage reported as passing. No actionable merge-blocking risk remains beyond normal checks and review.

Suggested reviewers: andrej730

🚥 Pre-merge checks | ✅ 5 ✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: applying format specifications to booleans instead of ignoring them.
Docstring Coverage ✅ Passed Docstring coverage is 83.33% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 6 functions across 2 files.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

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
youknowone force-pushed the fix/bool-format-spec branch from c344c34 to 8af4bd3 Compare August 21, 2026 18:12
youknowone merged commit 4c448c4 into RustPython:main Aug 22, 2026
27 checks passed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants


Back | FazBrowse Home | New Git URL