Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit b20df95

Browse files
committed
Issue #14849: setup Element data members to be assignable in subclasses
1 parent 77a1cf1 commit b20df95

2 files changed

Lines changed: 16 additions & 13 deletions

File tree

Lib/test/test_xml_etree.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1914,6 +1914,10 @@ class MyElement(ET.Element):
19141914
self.assertIsInstance(mye, MyElement)
19151915
self.assertEqual(mye.tag, 'foo')
19161916

1917+
# test that attribute assignment works (issue 14849)
1918+
mye.text = "joe"
1919+
self.assertEqual(mye.text, "joe")
1920+
19171921
def test_Element_subclass_constructor(self):
19181922
class MyElement(ET.Element):
19191923
def __init__(self, tag, attrib={}, **extra):

Modules/_elementtree.c

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1640,16 +1640,15 @@ element_getattro(ElementObject* self, PyObject* nameobj)
16401640
return res;
16411641
}
16421642

1643-
static int
1644-
element_setattr(ElementObject* self, const char* name, PyObject* value)
1643+
static PyObject*
1644+
element_setattro(ElementObject* self, PyObject* nameobj, PyObject* value)
16451645
{
1646-
if (value == NULL) {
1647-
PyErr_SetString(
1648-
PyExc_AttributeError,
1649-
"can't delete element attributes"
1650-
);
1651-
return -1;
1652-
}
1646+
char *name = "";
1647+
if (PyUnicode_Check(nameobj))
1648+
name = _PyUnicode_AsString(nameobj);
1649+
1650+
if (name == NULL)
1651+
return NULL;
16531652

16541653
if (strcmp(name, "tag") == 0) {
16551654
Py_DECREF(self->tag);
@@ -1671,10 +1670,10 @@ element_setattr(ElementObject* self, const char* name, PyObject* value)
16711670
Py_INCREF(self->extra->attrib);
16721671
} else {
16731672
PyErr_SetString(PyExc_AttributeError, name);
1674-
return -1;
1673+
return NULL;
16751674
}
16761675

1677-
return 0;
1676+
return NULL;
16781677
}
16791678

16801679
static PySequenceMethods element_as_sequence = {
@@ -1700,7 +1699,7 @@ static PyTypeObject Element_Type = {
17001699
(destructor)element_dealloc, /* tp_dealloc */
17011700
0, /* tp_print */
17021701
0, /* tp_getattr */
1703-
(setattrfunc)element_setattr, /* tp_setattr */
1702+
0, /* tp_setattr */
17041703
0, /* tp_reserved */
17051704
(reprfunc)element_repr, /* tp_repr */
17061705
0, /* tp_as_number */
@@ -1710,7 +1709,7 @@ static PyTypeObject Element_Type = {
17101709
0, /* tp_call */
17111710
0, /* tp_str */
17121711
(getattrofunc)element_getattro, /* tp_getattro */
1713-
0, /* tp_setattro */
1712+
(setattrofunc)element_setattro, /* tp_setattro */
17141713
0, /* tp_as_buffer */
17151714
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
17161715
/* tp_flags */

0 commit comments

Comments
 (0)