Skip to content

Make Sage reals and rationals more friendly to Python string formatting #27788

@slel

Description

@slel

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

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).

CC: @slel @jcamp0x2a

Component: numerical

Keywords: format

Issue created by migration from https://trac.sagemath.org/ticket/27788

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions