diff --git a/Lib/_pydecimal.py b/Lib/_pydecimal.py index 4b7bfd07887bd38..8b02f19c4e9d991 100644 --- a/Lib/_pydecimal.py +++ b/Lib/_pydecimal.py @@ -420,6 +420,9 @@ def sin(x): for key, value in kwargs.items(): if key not in _context_attributes: raise TypeError(f"'{key}' is an invalid keyword argument for this function") + if key in ('flags', 'traps') and not isinstance(value, dict): + # Accept a list of signals, like the Context constructor. + value = dict((s, int(s in value)) for s in _signals + value) setattr(ctx_manager.new_context, key, value) return ctx_manager diff --git a/Lib/test/test_decimal.py b/Lib/test/test_decimal.py index ef7aa5358b5cc64..c70bedda1fb687f 100644 --- a/Lib/test/test_decimal.py +++ b/Lib/test/test_decimal.py @@ -3851,6 +3851,19 @@ def test_localcontext_kwargs(self): self.assertEqual(ctx.capitals, 0) self.assertEqual(ctx.clamp, 1) + # gh-162491: flags and traps also accept a list of signals. + Overflow = self.decimal.Overflow + with self.decimal.localcontext( + flags=[self.decimal.Inexact], traps=[Overflow] + ) as ctx: + self.assertTrue(ctx.flags[self.decimal.Inexact]) + self.assertFalse(ctx.flags[Overflow]) + self.assertTrue(ctx.traps[Overflow]) + self.assertFalse(ctx.traps[self.decimal.DivisionByZero]) + with self.decimal.localcontext(traps=[]) as ctx: + self.assertFalse(any(ctx.traps.values())) + self.assertRaises(KeyError, self.decimal.localcontext, traps=[ValueError]) + self.assertRaises(TypeError, self.decimal.localcontext, precision=10) self.assertRaises(ValueError, self.decimal.localcontext, Emin=1) diff --git a/Misc/NEWS.d/next/Library/2026-11-23-20-00-00.gh-issue-162491.jyVmsQ.rst b/Misc/NEWS.d/next/Library/2026-11-23-20-00-00.gh-issue-162491.jyVmsQ.rst new file mode 100644 index 000000000000000..91cce7bf4650057 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-11-23-20-00-00.gh-issue-162491.jyVmsQ.rst @@ -0,0 +1,2 @@ +The pure-Python :func:`decimal.localcontext` now accepts a list of signals +for its *flags* and *traps* arguments, like the C implementation.