[New-bugs-announce] [issue47135] Allow decimal.localcontext to accept keyword arguments to set context attributes

Steven D'Aprano report at bugs.python.org
Sun Mar 27 06:16:04 EDT 2022


New submission from Steven D'Aprano <steve at pearwood.info>:

Whenever I use decimal and need to change the context temporarily, without fail I try to write

with decimal.localcontext(prec=10):
    ...

or similar. Then I get surprised that it fails, and re-write it as

with decimal.localcontext() as ctx:
    ctx.prec = 10
    ...

Let's make the first version work. localcontext should accept keyword arguments corresponding to the same arguments accepted by Context, and set them on the context given.

A proof-of-concept wrapper function:

def localcontext(ctx=None, **kwargs):
    if ctx is None:
        ctx = decimal.getcontext().copy()
    for key, value in kwargs.items():
        setattr(ctx, key, value)
    return decimal.localcontext(ctx)

I think this would be a valuable, and useful, improvement to the decimal API.

----------
components: Library (Lib)
messages: 416114
nosy: steven.daprano
priority: normal
severity: normal
status: open
title: Allow decimal.localcontext to accept keyword arguments to set context attributes
versions: Python 3.11

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue47135>
_______________________________________


More information about the New-bugs-announce mailing list