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?
If you replace
myconst = N(3/8)
bymyconst = float(3/8)
, there is no error. SageMath supports the three kinds of formatting, but unfortunately not for all data types.Thank you very much, @Juanjo and @eric_g! I suppose this is a matter of implementing the
__format__
special method for these data types.For now, I'm leaving the question open. But maybe the bug track is a good answer. If @eric_g decides to post it as answer, I can tick the question as answered.