Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions Lib/test/test_decimal.py
Original file line number Diff line number Diff line change
Expand Up @@ -3766,6 +3766,27 @@ def test_to_integral_value(self):
@requires_cdecimal
class CContextAPItests(ContextAPItests, unittest.TestCase):
decimal = C

def test_current_context_var_wrong_type(self):
Comment thread
0z5a marked this conversation as resolved.
Resolved
# gh-161387
if not self.decimal.HAVE_CONTEXTVAR:
self.skipTest("_decimal built without context variables")
value = object()
context_vars = [var for var in contextvars.copy_context()
if var.name == "decimal_context"]
self.assertTrue(context_vars)
tokens = [var.set(value) for var in context_vars]

def restore():
for var, token in zip(context_vars, tokens):
var.reset(token)

self.addCleanup(restore)
with self.assertRaisesRegex(TypeError, "got object"):
self.decimal.Decimal(1) + self.decimal.Decimal(2)
for var in context_vars:
self.assertIs(var.get(), value)

class PyContextAPItests(ContextAPItests, unittest.TestCase):
decimal = P

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix a crash in :mod:`decimal` when the internal ``decimal_context``
:class:`contextvars.ContextVar` holds a value that is not a context.
7 changes: 7 additions & 0 deletions Modules/_decimal/_decimal.c
Original file line number Diff line number Diff line change
Expand Up @@ -1997,6 +1997,13 @@ current_context(decimal_state *state)
}

if (tl_context != NULL) {
if (!PyDecContext_Check(state, tl_context)) {
PyErr_Format(PyExc_TypeError,
"current decimal context must be a Context "
"instance, got %T", tl_context);
Py_DECREF(tl_context);
Comment thread
sobolevn marked this conversation as resolved.
Resolved
return NULL;
}
return tl_context;
}

Expand Down
Loading