Skip to content

Commit 30b61b5

Browse files
orenmnserhiy-storchaka
authored andcommitted
bpo-31490: Fix an assertion failure in ctypes in case an _anonymous_ attr is defined only outside _fields_. (#3615)
1 parent a6bb313 commit 30b61b5

File tree

3 files changed

+25
-1
lines changed

3 files changed

+25
-1
lines changed

‎Lib/ctypes/test/test_anon.py‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import unittest
2+
import test.support
23
from ctypes import *
34

45
class AnonTest(unittest.TestCase):
@@ -35,6 +36,18 @@ def test_anon_nonmember(self):
3536
{"_fields_": [],
3637
"_anonymous_": ["x"]}))
3738

39+
@test.support.cpython_only
40+
def test_issue31490(self):
41+
# There shouldn't be an assertion failure in case the class has an
42+
# attribute whose name is specified in _anonymous_ but not in _fields_.
43+
44+
# AttributeError: 'x' is specified in _anonymous_ but not in _fields_
45+
with self.assertRaises(AttributeError):
46+
class Name(Structure):
47+
_fields_ = []
48+
_anonymous_ = ["x"]
49+
x = 42
50+
3851
def test_nested(self):
3952
class ANON_S(Structure):
4053
_fields_ = [("a", c_int)]
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fix an assertion failure in `ctypes` class definition, in case the class has
2+
an attribute whose name is specified in ``_anonymous_`` but not in
3+
``_fields_``. Patch by Oren Milman.

‎Modules/_ctypes/stgdict.c‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -302,7 +302,15 @@ MakeAnonFields(PyObject *type)
302302
Py_DECREF(anon_names);
303303
return -1;
304304
}
305-
assert(Py_TYPE(descr) == &PyCField_Type);
305+
if (Py_TYPE(descr) != &PyCField_Type) {
306+
PyErr_Format(PyExc_AttributeError,
307+
"'%U' is specified in _anonymous_ but not in "
308+
"_fields_",
309+
fname);
310+
Py_DECREF(anon_names);
311+
Py_DECREF(descr);
312+
return -1;
313+
}
306314
descr->anonymous = 1;
307315

308316
/* descr is in the field descriptor. */

0 commit comments

Comments
 (0)