Skip to content

Commit ccb6fd2

Browse files
skdas20claude
andcommitted
gh-162491: Accept a list of signals in _pydecimal.localcontext()
localcontext() set the flags and traps keyword arguments directly on the new context, which only accepts a signal dict, so passing a list of signals raised TypeError. Convert a list the same way the Context constructor does, matching the C implementation. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent a46c65c commit ccb6fd2

3 files changed

Lines changed: 18 additions & 0 deletions

File tree

‎Lib/_pydecimal.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -420,6 +420,9 @@ def sin(x):
420420
for key, value in kwargs.items():
421421
if key not in _context_attributes:
422422
raise TypeError(f"'{key}' is an invalid keyword argument for this function")
423+
if key in ('flags', 'traps') and isinstance(value, list):
424+
# Accept a list of signals, like the Context constructor.
425+
value = dict((s, int(s in value)) for s in _signals + value)
423426
setattr(ctx_manager.new_context, key, value)
424427
return ctx_manager
425428

‎Lib/test/test_decimal.py‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3851,6 +3851,19 @@ def test_localcontext_kwargs(self):
38513851
self.assertEqual(ctx.capitals, 0)
38523852
self.assertEqual(ctx.clamp, 1)
38533853

3854+
# gh-162491: flags and traps also accept a list of signals.
3855+
Overflow = self.decimal.Overflow
3856+
with self.decimal.localcontext(
3857+
flags=[self.decimal.Inexact], traps=[Overflow]
3858+
) as ctx:
3859+
self.assertTrue(ctx.flags[self.decimal.Inexact])
3860+
self.assertFalse(ctx.flags[Overflow])
3861+
self.assertTrue(ctx.traps[Overflow])
3862+
self.assertFalse(ctx.traps[self.decimal.DivisionByZero])
3863+
with self.decimal.localcontext(traps=[]) as ctx:
3864+
self.assertFalse(any(ctx.traps.values()))
3865+
self.assertRaises(KeyError, self.decimal.localcontext, traps=[ValueError])
3866+
38543867
self.assertRaises(TypeError, self.decimal.localcontext, precision=10)
38553868

38563869
self.assertRaises(ValueError, self.decimal.localcontext, Emin=1)
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
The pure-Python :func:`decimal.localcontext` now accepts a list of signals
2+
for its *flags* and *traps* arguments, like the C implementation.

0 commit comments

Comments
 (0)