Opened 2 years ago
Last modified 8 months ago
#27788 new enhancement
Make Sage reals and rationals more friendly to Python string formatting
Reported by: | slelievre | Owned by: | |
---|---|---|---|
Priority: | major | Milestone: | |
Component: | numerical | Keywords: | format |
Cc: | slelievre, gh-jcamp0x2a | Merged in: | |
Authors: | Reviewers: | ||
Report Upstream: | N/A | Work issues: | |
Branch: | Commit: | ||
Dependencies: | Stopgaps: |
Description (last modified by )
Let us make Sage reals and rationals more friendly to formatting commands that expect Python floats.
For example, with a Python float one can do
sage: a = 1.25r sage: "{:0.3f}".format(a) '1.250'
but a similar command fails for a Sage real or rational:
sage: a = 1.25 sage: "{:0.3f}".format(a) Traceback (most recent call last) ... TypeError: unsupported format string passed to sage.rings.real_mpfr.RealLiteral.__format__
sage: a = 5/4 sage: "{:0.3f}".format(a) Traceback (most recent call last) ... TypeError: unsupported format string passed to sage.rings.rational.Rational.__format__
This puzzles users especially when using Python packages with Sage. As things stand one needs to know to work around Sage's preparser.
For example this came up in
- Ask Sage question 46408: tqdm's "total" parameter bug
- Ask Sage question 52617: f string float not working
The case of Sage integers was dealt with in #12788 and can provide inspiration.
We could also consider doing the same for number field elements, algebraic numbers, complex floating-point numbers, continued fractions... and other numbers in Sage for which it makes sense.
This is part of #29728 (Meta-ticket: improve compatibility with the Python library).
Change History (5)
comment:1 Changed 23 months ago by
- Milestone sage-8.8 deleted
comment:2 Changed 10 months ago by
- Description modified (diff)
comment:3 Changed 8 months ago by
This should be easily resolved by implementing __format__
on the relevant types. This might be a good beginner project.
comment:4 Changed 8 months ago by
- Cc gh-jcamp0x2a added
comment:5 Changed 8 months ago by
#30515 now has an implementation for real and complex numbers.
Implementing this for rational numbers is a bit tricky since they have arbitrary precision, so fully parsing the format specificier seems to be necessary. Once the precision is known, one could convert to a RealField
of suitable precision and reuse the __format__
of its elements, but there may be some corner cases.
As the Sage-8.8 release milestone is pending, we should delete the sage-8.8 milestone for tickets that are not actively being worked on or that still require significant work to move forward. If you feel that this ticket should be included in the next Sage release at the soonest please set its milestone to the next release milestone (sage-8.9).