Skip to content

Commit 19e99ea

Browse files
committed
gh-99275: Fix SystemError in ctypes during __initsubclass__
1 parent c43714f commit 19e99ea

File tree

3 files changed

+15
-1
lines changed

3 files changed

+15
-1
lines changed

Lib/test/test_ctypes/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
@@ -425,8 +425,11 @@ PyCStructUnionType_update_stgdict(PyObject *type, PyObject *fields, int isStruct
425425
}
426426

427427
stgdict = PyType_stgdict(type);
428-
if (!stgdict)
428+
if (!stgdict) {
429+
PyErr_SetString(PyExc_TypeError,
430+
"ctypes state is not initialized");
429431
return -1;
432+
}
430433
/* If this structure/union is already marked final we cannot assign
431434
_fields_ anymore. */
432435

0 commit comments

Comments
 (0)