summaryrefslogtreecommitdiffstats
path: root/Lib/_pydecimal.py
diff options
context:
space:
mode:
authorSam Ezeh <sam.z.ezeh@gmail.com>2022-04-22 04:27:15 (GMT)
committerGitHub <noreply@github.com>2022-04-22 04:27:15 (GMT)
commitbcf14ae4336fced718c00edc34b9191c2b48525a (patch)
tree7067583bc8a296b111e8858286b4b1d00bad97d1 /Lib/_pydecimal.py
parent5e130a8da4e4f13444ec20dfe88a3e2e070005ca (diff)
downloadcpython-bcf14ae4336fced718c00edc34b9191c2b48525a.zip
cpython-bcf14ae4336fced718c00edc34b9191c2b48525a.tar.gz
cpython-bcf14ae4336fced718c00edc34b9191c2b48525a.tar.bz2
gh-91291: Accept attributes as keyword arguments in decimal.localcontext (#32242)
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
Diffstat (limited to 'Lib/_pydecimal.py')
-rw-r--r--Lib/_pydecimal.py16
1 files changed, 13 insertions, 3 deletions
diff --git a/Lib/_pydecimal.py b/Lib/_pydecimal.py
index 89646fa..f9d6c99 100644
--- a/Lib/_pydecimal.py
+++ b/Lib/_pydecimal.py
@@ -441,6 +441,10 @@ import contextvars
_current_context_var = contextvars.ContextVar('decimal_context')
+_context_attributes = frozenset(
+ ['prec', 'Emin', 'Emax', 'capitals', 'clamp', 'rounding', 'flags', 'traps']
+)
+
def getcontext():
"""Returns this thread's context.
@@ -464,7 +468,7 @@ def setcontext(context):
del contextvars # Don't contaminate the namespace
-def localcontext(ctx=None):
+def localcontext(ctx=None, **kwargs):
"""Return a context manager for a copy of the supplied context
Uses a copy of the current context if no context is specified
@@ -500,8 +504,14 @@ def localcontext(ctx=None):
>>> print(getcontext().prec)
28
"""
- if ctx is None: ctx = getcontext()
- return _ContextManager(ctx)
+ if ctx is None:
+ ctx = getcontext()
+ ctx_manager = _ContextManager(ctx)
+ for key, value in kwargs.items():
+ if key not in _context_attributes:
+ raise TypeError(f"'{key}' is an invalid keyword argument for this function")
+ setattr(ctx_manager.new_context, key, value)
+ return ctx_manager
##### Decimal class #######################################################