Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Sage doesn't support completely modern string formatting

Hello, Sage community!

Modern Python 3 defines various way to printing formatted strings. Here are some examples:

myconst = N(3/8)
print('Hello, world of %.2f'%(myconst))
print('Hello, world of {:.2f}'.format(myconst))
print(f'Hello, world of {myconst:.2f}')

The first example should be the most known and common. The second example uses the format method, and the third uses f-strings. Unfortunately, these two last forms of formatted strings aren't supported by Sage. For example,

print('Hello, world of {:.2f}'.format(myconst))

prints the following traceback

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-6-6336f0c43d90> in <module>()
----> 1 print('Hello, world of {:.2f}'.format(myconst))

TypeError: unsupported format string passed to sage.rings.real_mpfr.RealNumber.__format__

Exactly the same error and traceback are issued with the third example.

Now, on the other hand, if no string conversion specification is used, these work fine:

print('Hello, world of {}'.format(myconst))
print(f'Hello, world of {myconst}')

Also, try using pi instead of myconst. Works fine withN(pi), but not with N(myconst); this seems an inconsistent behavior.

Is there some workaround for this problem? Should it be reported as a bug/enhancement?