Skip to content

Commit bf76d9b

Browse files
gh-99275: Fix SystemError in ctypes during __initsubclass__ (GH-99283)
(cherry picked from commit 343eb0f) Co-authored-by: Nikita Sobolev <[email protected]>
1 parent 72d356e commit bf76d9b

File tree

3 files changed

+15
-1
lines changed

3 files changed

+15
-1
lines changed

Lib/ctypes/test/test_struct_fields.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,15 @@ class X(Structure):
5454
x.char = b'a\0b\0'
5555
self.assertEqual(bytes(x), b'a\x00###')
5656

57+
def test_gh99275(self):
58+
class BrokenStructure(Structure):
59+
def __init_subclass__(cls, **kwargs):
60+
cls._fields_ = [] # This line will fail, `stgdict` is not ready
61+
62+
with self.assertRaisesRegex(TypeError,
63+
'ctypes state is not initialized'):
64+
class Subclass(BrokenStructure): ...
65+
5766
# __set__ and __get__ should raise a TypeError in case their self
5867
# argument is not a ctype instance.
5968
def test___set__(self):
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix ``SystemError`` in :mod:`ctypes` when exception was not set during
2+
``__initsubclass__``.

Modules/_ctypes/stgdict.c

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -430,8 +430,11 @@ PyCStructUnionType_update_stgdict(PyObject *type, PyObject *fields, int isStruct
430430
}
431431

432432
stgdict = PyType_stgdict(type);
433-
if (!stgdict)
433+
if (!stgdict) {
434+
PyErr_SetString(PyExc_TypeError,
435+
"ctypes state is not initialized");
434436
return -1;
437+
}
435438
/* If this structure/union is already marked final we cannot assign
436439
_fields_ anymore. */
437440

0 commit comments

Comments
 (0)