Skip to content

Incompatible (wrt floats) processing of alignment and '0' flag in Fraction's formatting #130716

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
skirpichev opened this issue Mar 1, 2025 · 0 comments
Labels
docs Documentation in the Doc dir interpreter-core (Objects, Python, Grammar, and Parser dirs) type-bug An unexpected behavior, bug, or error

Comments

@skirpichev
Copy link
Member

skirpichev commented Mar 1, 2025

Bug report

Bug description:

>>> x = Fraction(1, 3)
>>> f"{x:_>010f}"
Traceback (most recent call last):
  File "<python-input-2>", line 1, in <module>
    f"{x:_>010f}"
      ^^^^^^^^^^
  File "/home/sk/src/cpython/Lib/fractions.py", line 600, in __format__
    raise ValueError(
    ...<2 lines>...
    )
ValueError: Invalid format specifier '_>010f' for object of type 'Fraction'
>>> f"{float(x):_>010f}"
'__0.333333'

While not being documented, this behavior is intentional (see #100161): "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." In floats case, "0" flag is just ignored if the fill character (and, thus, alignment) already specified.

Maybe it's not a bad idea to use Fraction's behavior for floats too, i.e. deprecate this silent resolution of ambiguity. Or just document this discrepancy.

Decimal's behave here like Fraction's:

>>> f"{Decimal(1.25):_>010f}"
Traceback (most recent call last):
  File "<python-input-5>", line 1, in <module>
    f"{Decimal(1.25):_>010f}"
      ^^^^^^^^^^^^^^^^^^^^^^
ValueError: invalid format string

CPython versions tested on:

CPython main branch

Operating systems tested on:

No response

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
docs Documentation in the Doc dir interpreter-core (Objects, Python, Grammar, and Parser dirs) type-bug An unexpected behavior, bug, or error
Projects
Status: Todo
Development

No branches or pull requests

1 participant