gh-53032: support IEEE 754 contexts in the decimal module (#122003)

This was in C version from beginning, but available only
on conditional compilation (EXTRA_FUNCTIONALITY).  Current
patch adds function to create IEEE contexts to the
pure-python module as well.

Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com>
This commit is contained in:
Sergey B Kirpichev 2025-04-28 16:05:56 +03:00 committed by GitHub
parent e20ca6d1b0
commit 5bf0f3666e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
7 changed files with 101 additions and 65 deletions

View file

@ -38,10 +38,10 @@ __all__ = [
'ROUND_FLOOR', 'ROUND_UP', 'ROUND_HALF_DOWN', 'ROUND_05UP',
# Functions for manipulating contexts
'setcontext', 'getcontext', 'localcontext',
'setcontext', 'getcontext', 'localcontext', 'IEEEContext',
# Limits for the C version for compatibility
'MAX_PREC', 'MAX_EMAX', 'MIN_EMIN', 'MIN_ETINY',
'MAX_PREC', 'MAX_EMAX', 'MIN_EMIN', 'MIN_ETINY', 'IEEE_CONTEXT_MAX_BITS',
# C version: compile time choice that enables the thread local context (deprecated, now always true)
'HAVE_THREADS',
@ -83,10 +83,12 @@ if sys.maxsize == 2**63-1:
MAX_PREC = 999999999999999999
MAX_EMAX = 999999999999999999
MIN_EMIN = -999999999999999999
IEEE_CONTEXT_MAX_BITS = 512
else:
MAX_PREC = 425000000
MAX_EMAX = 425000000
MIN_EMIN = -425000000
IEEE_CONTEXT_MAX_BITS = 256
MIN_ETINY = MIN_EMIN - (MAX_PREC-1)
@ -417,6 +419,27 @@ def localcontext(ctx=None, **kwargs):
return ctx_manager
def IEEEContext(bits, /):
"""
Return a context object initialized to the proper values for one of the
IEEE interchange formats. The argument must be a multiple of 32 and less
than IEEE_CONTEXT_MAX_BITS.
"""
if bits <= 0 or bits > IEEE_CONTEXT_MAX_BITS or bits % 32:
raise ValueError("argument must be a multiple of 32, "
f"with a maximum of {IEEE_CONTEXT_MAX_BITS}")
ctx = Context()
ctx.prec = 9 * (bits//32) - 2
ctx.Emax = 3 * (1 << (bits//16 + 3))
ctx.Emin = 1 - ctx.Emax
ctx.rounding = ROUND_HALF_EVEN
ctx.clamp = 1
ctx.traps = dict.fromkeys(_signals, False)
return ctx
##### Decimal class #######################################################
# Do not subclass Decimal from numbers.Real and do not register it as such