Add pretty_dps context property to control number of printed digits

Closes #921
This commit is contained in:
Sergey B Kirpichev
2025-03-30 08:42:09 +03:00
parent 8c6f6603ad
commit a14901da43
4 changed files with 19 additions and 3 deletions
+2
View File
@@ -221,6 +221,8 @@ Setting the ``mp.pretty`` option will use the ``str()``-style output for ``repr(
>>> mpf(0.6)
mpf('0.59999999999999998')
To use enough digits to be able recreate value exactly, set ``mp.pretty_dps`` to ``"repr"``.
The number of digits with which numbers are printed by default is determined by
the working precision. To specify the number of digits to show without
changing the working precision, use :func:`format syntax support
+1
View File
@@ -57,6 +57,7 @@ def main():
lines.append(f'mp.prec = {args.prec}')
if not args.no_pretty:
lines.append('mp.pretty = True')
lines.append('mp.pretty_dps = "repr"')
try:
import IPython
+15 -2
View File
@@ -130,7 +130,9 @@ class _mpf(mpnumeric):
def __repr__(s):
if s.context.pretty:
return str(s)
ndigits = (s.context._repr_digits
if s.context._pretty_repr_dps else s.context._str_digits)
return to_str(s._mpf_, ndigits)
return "mpf('%s')" % to_str(s._mpf_, s.context._repr_digits)
def __str__(s): return to_str(s._mpf_, s.context._str_digits)
@@ -514,7 +516,9 @@ class _mpc(mpnumeric):
def __repr__(s):
if s.context.pretty:
return str(s)
ndigits = (s.context._repr_digits
if s.context._pretty_repr_dps else s.context._str_digits)
return "(%s)" % mpc_to_str(s._mpc_, ndigits)
r = repr(s.real)[4:-1]
i = repr(s.imag)[4:-1]
return "%s(real=%s, imag=%s)" % (type(s).__name__, r, i)
@@ -709,6 +713,7 @@ class PythonMPContext:
ctx.constant = type('constant', (_constant,), {})
ctx.constant._ctxdata = [ctx.mpf, new, ctx._prec_rounding]
ctx.constant.context = ctx
ctx._pretty_repr_dps = False
def make_mpf(ctx, v):
a = new(ctx.mpf)
@@ -736,6 +741,14 @@ class PythonMPContext:
prec = property(lambda ctx: ctx._prec, _set_prec)
dps = property(lambda ctx: ctx._dps, _set_dps)
def _set_pretty_dps(ctx, v):
ctx._pretty_repr_dps = True if v == 'repr' else False
def _get_pretty_dps(ctx):
return 'repr' if ctx._pretty_repr_dps else 'str'
pretty_dps = property(_get_pretty_dps, _set_pretty_dps)
def convert(ctx, x, strings=True):
"""
Converts *x* to an ``mpf`` or ``mpc``. If *x* is of type ``mpf``,
+1 -1
View File
@@ -111,7 +111,7 @@ def test_bare_console_pretty():
assert c.expect_exact('>>> ') == 0
assert c.send("10.9\r\n") == 6
assert c.expect_exact("10.9\r\n>>> ") == 0
assert c.expect_exact("10.899999999999999999999999999995\r\n>>> ") == 0
assert c.send("def f():\r\n x = ?\r\n\r\n") == 21
assert c.expect('SyntaxError:') == 0