Ask Your Question
2

Sage doesn't support completely modern string formatting

asked 2020-03-03 18:09:36 -0600

dsejas gravatar image

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?

edit retag flag offensive close merge delete

Comments

If you replace myconst = N(3/8) by myconst = float(3/8), there is no error. SageMath supports the three kinds of formatting, but unfortunately not for all data types.

Juanjo gravatar imageJuanjo ( 2020-03-04 02:49:22 -0600 )edit

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.

dsejas gravatar imagedsejas ( 2020-03-04 10:19:54 -0600 )edit

1 answer

Sort by ยป oldest newest most voted
1

answered 2020-03-04 09:17:46 -0600

eric_g gravatar image

This bug is being tracked at https://trac.sagemath.org/ticket/29212

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2020-03-03 18:09:36 -0600

Seen: 227 times

Last updated: Mar 03