gh-91291: Accept attributes as keyword arguments in decimal.localcontext (#32242)

Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
This commit is contained in:
Sam Ezeh 2022-04-22 05:27:15 +01:00 committed by GitHub
parent 5e130a8da4
commit bcf14ae433
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 161 additions and 62 deletions

View file

@ -925,12 +925,13 @@ Each thread has its own current context which is accessed or changed using the
You can also use the :keyword:`with` statement and the :func:`localcontext`
function to temporarily change the active context.
.. function:: localcontext(ctx=None)
.. function:: localcontext(ctx=None, \*\*kwargs)
Return a context manager that will set the current context for the active thread
to a copy of *ctx* on entry to the with-statement and restore the previous context
when exiting the with-statement. If no context is specified, a copy of the
current context is used.
current context is used. The *kwargs* argument is used to set the attributes
of the new context.
For example, the following code sets the current decimal precision to 42 places,
performs a calculation, and then automatically restores the previous context::
@ -942,6 +943,21 @@ function to temporarily change the active context.
s = calculate_something()
s = +s # Round the final result back to the default precision
Using keyword arguments, the code would be the following::
from decimal import localcontext
with localcontext(prec=42) as ctx:
s = calculate_something()
s = +s
Raises :exc:`TypeError` if *kwargs* supplies an attribute that :class:`Context` doesn't
support. Raises either :exc:`TypeError` or :exc:`ValueError` if *kwargs* supplies an
invalid value for an attribute.
.. versionchanged:: 3.11
:meth:`localcontext` now supports setting context attributes through the use of keyword arguments.
New contexts can also be created using the :class:`Context` constructor
described below. In addition, the module provides three pre-made contexts: