diff --git a/Include/internal/pycore_global_objects_fini_generated.h b/Include/internal/pycore_global_objects_fini_generated.h index 483a1dc58791cd5..fa662d39d95985f 100644 --- a/Include/internal/pycore_global_objects_fini_generated.h +++ b/Include/internal/pycore_global_objects_fini_generated.h @@ -315,6 +315,7 @@ _PyStaticObjects_CheckAll(PyInterpreterState *interp) { _PyStaticObject_CheckUnicodeSingleton((PyObject *)&_Py_ID(ast), "ast", 3); _PyStaticObject_CheckUnicodeSingleton((PyObject *)&_Py_ID(athrow), "athrow", 6); _PyStaticObject_CheckUnicodeSingleton((PyObject *)&_Py_ID(attr), "attr", 4); + _PyStaticObject_CheckUnicodeSingleton((PyObject *)&_Py_ID(attrib), "attrib", 6); _PyStaticObject_CheckUnicodeSingleton((PyObject *)&_Py_ID(attribute), "attribute", 9); _PyStaticObject_CheckUnicodeSingleton((PyObject *)&_Py_ID(autocommit), "autocommit", 10); _PyStaticObject_CheckUnicodeSingleton((PyObject *)&_Py_ID(backtick), "backtick", 8); diff --git a/Include/internal/pycore_global_strings.h b/Include/internal/pycore_global_strings.h index 949e19196dc5279..3038184fc287b5a 100644 --- a/Include/internal/pycore_global_strings.h +++ b/Include/internal/pycore_global_strings.h @@ -327,6 +327,7 @@ struct _Py_global_strings { STRUCT_FOR_ID(ast) STRUCT_FOR_ID(athrow) STRUCT_FOR_ID(attr) + STRUCT_FOR_ID(attrib) STRUCT_FOR_ID(attribute) STRUCT_FOR_ID(autocommit) STRUCT_FOR_ID(backtick) diff --git a/Include/internal/pycore_runtime_init_generated.h b/Include/internal/pycore_runtime_init_generated.h index 4ee954942521ae1..d5e724a2c5f74df 100644 --- a/Include/internal/pycore_runtime_init_generated.h +++ b/Include/internal/pycore_runtime_init_generated.h @@ -1602,6 +1602,7 @@ extern "C" { INIT_ID(ast), \ INIT_ID(athrow), \ INIT_ID(attr), \ + INIT_ID(attrib), \ INIT_ID(attribute), \ INIT_ID(autocommit), \ INIT_ID(backtick), \ diff --git a/Include/internal/pycore_unicodeobject_generated.h b/Include/internal/pycore_unicodeobject_generated.h index 3aad3345abc4d07..01765d8a849029d 100644 --- a/Include/internal/pycore_unicodeobject_generated.h +++ b/Include/internal/pycore_unicodeobject_generated.h @@ -279,6 +279,7 @@ _PyUnicode_InitStaticStrings(PyInterpreterState *interp) { offsetof(struct _Py_global_strings, identifiers._py_ast._ascii.ob_base), offsetof(struct _Py_global_strings, identifiers._py_athrow._ascii.ob_base), offsetof(struct _Py_global_strings, identifiers._py_attr._ascii.ob_base), + offsetof(struct _Py_global_strings, identifiers._py_attrib._ascii.ob_base), offsetof(struct _Py_global_strings, identifiers._py_attribute._ascii.ob_base), offsetof(struct _Py_global_strings, identifiers._py_autocommit._ascii.ob_base), offsetof(struct _Py_global_strings, identifiers._py_backtick._ascii.ob_base), diff --git a/Lib/test/test_xml_etree.py b/Lib/test/test_xml_etree.py index a5d4d5f65feb38d..67761f78ffb1568 100644 --- a/Lib/test/test_xml_etree.py +++ b/Lib/test/test_xml_etree.py @@ -3027,6 +3027,10 @@ def f(): class BasicElementTest(ElementTestCase, unittest.TestCase): + def test_extra_keys_must_be_strings(self): + with self.assertRaisesRegex(TypeError, "keywords must be strings"): + ET.Element("tag", **{ET.QName("key"): "value"}) + def test___init__(self): tag = "foo" attrib = { "zix": "wyp" } diff --git a/Misc/NEWS.d/next/Library/2026-11-25-12-00-00.gh-issue-162350.7lKjHs.rst b/Misc/NEWS.d/next/Library/2026-11-25-12-00-00.gh-issue-162350.7lKjHs.rst new file mode 100644 index 000000000000000..d7dc994716970ce --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-11-25-12-00-00.gh-issue-162350.7lKjHs.rst @@ -0,0 +1,3 @@ +Raise :exc:`TypeError` for non-string keys in *extra* when calling +:class:`xml.etree.ElementTree.Element`, as the Python implementation already +did. Pass such keys in *attrib* instead. diff --git a/Modules/_elementtree.c b/Modules/_elementtree.c index 2195010261678f7..f630eb2784b6be6 100644 --- a/Modules/_elementtree.c +++ b/Modules/_elementtree.c @@ -19,6 +19,7 @@ #include "pycore_ceval.h" // _Py_EnterRecursiveCall() #include "pycore_dict.h" // _PyDict_CopyAsDict() #include "pycore_pyhash.h" // _Py_HashSecret +#include "pycore_runtime.h" // _Py_ID() #include "pycore_tuple.h" // _PyTuple_FromPair #include "pycore_weakref.h" // FT_CLEAR_WEAKREFS() @@ -377,7 +378,7 @@ static PyObject* get_attrib_from_keywords(PyObject *kwds) { PyObject *attrib; - if (PyDict_PopString(kwds, "attrib", &attrib) < 0) { + if (PyDict_Pop(kwds, &_Py_ID(attrib), &attrib) < 0) { return NULL; } @@ -393,16 +394,16 @@ get_attrib_from_keywords(PyObject *kwds) return NULL; } Py_SETREF(attrib, _PyDict_CopyAsDict(attrib)); + if (attrib == NULL) { + return NULL; + } + if (PyDict_Update(attrib, kwds) < 0) { + Py_DECREF(attrib); + return NULL; + } + return attrib; } - else { - attrib = PyDict_New(); - } - - if (attrib != NULL && PyDict_Update(attrib, kwds) < 0) { - Py_DECREF(attrib); - return NULL; - } - return attrib; + return PyDict_Copy(kwds); } /*[clinic input] @@ -413,15 +414,37 @@ class _elementtree.XMLParser "XMLParserObject *" "clinic_state()->XMLParser_Type [clinic start generated code]*/ /*[clinic end generated code: output=da39a3ee5e6b4b0d input=6c83ea832d2b0ef1]*/ +/*[clinic input] +@vectorcall +@text_signature "(tag, /, attrib={}, **extra)" +_elementtree.Element.__init__ + + tag: object + attrib: object(c_default="NULL") = {} + / + **extra as kwds: dict + +An XML element. + +This class is the reference implementation of the Element interface. + +An element's length is its number of subelements. That means if you +want to check if an element is truly empty, you should check BOTH +its length AND its text attribute. + +*tag* is the element name. *attrib* is an optional dictionary +containing element attributes. *extra* are additional element +attributes given as keyword arguments. + +Example form: + text...tail +[clinic start generated code]*/ + static int -element_init(PyObject *self, PyObject *args, PyObject *kwds) +_elementtree_Element___init___impl(ElementObject *self, PyObject *tag, + PyObject *attrib, PyObject *kwds) +/*[clinic end generated code: output=3f81773682edf81e input=58fd874d3a42aca3]*/ { - PyObject *tag; - PyObject *attrib = NULL; - ElementObject *self_elem; - - if (!PyArg_ParseTuple(args, "O|O:Element", &tag, &attrib)) - return -1; if (attrib != NULL && !PyAnyDict_Check(attrib)) { PyErr_Format(PyExc_TypeError, "Element() argument 2 must be dict or frozendict, not %T", @@ -447,10 +470,8 @@ element_init(PyObject *self, PyObject *args, PyObject *kwds) return -1; } - self_elem = (ElementObject *)self; - if (attrib != NULL && !is_empty_dict(attrib)) { - if (create_extra(self_elem, attrib) < 0) { + if (create_extra(self, attrib) < 0) { Py_DECREF(attrib); return -1; } @@ -460,10 +481,10 @@ element_init(PyObject *self, PyObject *args, PyObject *kwds) Py_XDECREF(attrib); /* Replace the objects already pointed to by tag, text and tail. */ - Py_XSETREF(self_elem->tag, Py_NewRef(tag)); + Py_XSETREF(self->tag, Py_NewRef(tag)); - _set_joined_ptr(&self_elem->text, Py_NewRef(Py_None)); - _set_joined_ptr(&self_elem->tail, Py_NewRef(Py_None)); + _set_joined_ptr(&self->text, Py_NewRef(Py_None)); + _set_joined_ptr(&self->tail, Py_NewRef(Py_None)); return 0; } @@ -4453,27 +4474,8 @@ static PyGetSetDef element_getsetlist[] = { {NULL}, }; -PyDoc_STRVAR(element_doc, -"Element(tag, attrib={}, **extra)\n" -"--\n" -"\n" -"An XML element.\n" -"\n" -"This class is the reference implementation of the Element interface.\n" -"\n" -"An element's length is its number of subelements. That means if you\n" -"want to check if an element is truly empty, you should check BOTH\n" -"its length AND its text attribute.\n" -"\n" -"*tag* is the element name. *attrib* is an optional dictionary\n" -"containing element attributes. *extra* are additional element\n" -"attributes given as keyword arguments.\n" -"\n" -"Example form:\n" -" text...tail"); - static PyType_Slot element_slots[] = { - {Py_tp_doc, (void *)element_doc}, + {Py_tp_doc, (void *)_elementtree_Element___init____doc__}, {Py_tp_dealloc, element_dealloc}, {Py_tp_repr, element_repr}, {Py_tp_getattro, PyObject_GenericGetAttr}, @@ -4482,7 +4484,8 @@ static PyType_Slot element_slots[] = { {Py_tp_methods, element_methods}, {Py_tp_members, element_members}, {Py_tp_getset, element_getsetlist}, - {Py_tp_init, element_init}, + {Py_tp_init, _elementtree_Element___init__}, + {Py_tp_vectorcall, _elementtree_Element_vectorcall}, {Py_tp_alloc, PyType_GenericAlloc}, {Py_tp_new, element_new}, {Py_sq_length, element_length}, diff --git a/Modules/clinic/_elementtree.c.h b/Modules/clinic/_elementtree.c.h index afc9daa5288f2c5..02192ca334d4cea 100644 --- a/Modules/clinic/_elementtree.c.h +++ b/Modules/clinic/_elementtree.c.h @@ -4,12 +4,112 @@ preserve #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE) # include "pycore_gc.h" // PyGC_Head -# include "pycore_runtime.h" // _Py_ID() #endif #include "pycore_abstract.h" // _PyNumber_Index() #include "pycore_modsupport.h" // _PyArg_CheckPositional() +#include "pycore_runtime.h" // _Py_SINGLETON() #include "pycore_unicodeobject.h" // _PyUnicode_AsUTF8NoNUL() +PyDoc_STRVAR(_elementtree_Element___init____doc__, +"Element(tag, /, attrib={}, **extra)\n" +"--\n" +"\n" +"An XML element.\n" +"\n" +"This class is the reference implementation of the Element interface.\n" +"\n" +"An element\'s length is its number of subelements. That means if you\n" +"want to check if an element is truly empty, you should check BOTH\n" +"its length AND its text attribute.\n" +"\n" +"*tag* is the element name. *attrib* is an optional dictionary\n" +"containing element attributes. *extra* are additional element\n" +"attributes given as keyword arguments.\n" +"\n" +"Example form:\n" +" text...tail"); + +static int +_elementtree_Element___init___impl(ElementObject *self, PyObject *tag, + PyObject *attrib, PyObject *kwds); + +static int +_elementtree_Element___init__(PyObject *self, PyObject *args, PyObject *kwargs) +{ + int return_value = -1; + PyObject *tag; + PyObject *attrib = NULL; + PyObject *__clinic_kwds = NULL; + + if (!_PyArg_CheckPositional("Element", PyTuple_GET_SIZE(args), 1, 2)) { + goto exit; + } + tag = PyTuple_GET_ITEM(args, 0); + if (PyTuple_GET_SIZE(args) < 2) { + goto skip_optional; + } + attrib = PyTuple_GET_ITEM(args, 1); +skip_optional: + __clinic_kwds = Py_XNewRef(kwargs); + return_value = _elementtree_Element___init___impl((ElementObject *)self, tag, attrib, __clinic_kwds); + +exit: + /* Cleanup for kwds */ + Py_XDECREF(__clinic_kwds); + + return return_value; +} + +static PyObject * +_elementtree_Element_vectorcall(PyObject *type, PyObject *const *args, + size_t nargsf, PyObject *kwnames) +{ + PyObject *return_value = NULL; + Py_ssize_t nargs = PyVectorcall_NARGS(nargsf); + PyObject *self; + int _result; + PyObject *tag; + PyObject *attrib = NULL; + PyObject *__clinic_kwds = NULL; + + assert(_PyType_CAST(type)->tp_init == _elementtree_Element___init__); + /* Make sure the type object is immutable: the generated + * vectorcall doesn't deal e.g. with users reassigning __init__. */ + assert(PyType_HasFeature(_PyType_CAST(type), Py_TPFLAGS_IMMUTABLETYPE)); + if (!_PyArg_CheckPositional("Element", nargs, 1, 2)) { + goto exit; + } + tag = args[0]; + if (nargs < 2) { + goto skip_optional; + } + attrib = args[1]; +skip_optional: + if (kwnames != NULL) { + __clinic_kwds = _PyStack_AsDict(args + nargs, kwnames); + if (__clinic_kwds == NULL) { + goto exit; + } + } + self = _PyType_CAST(type)->tp_new(_PyType_CAST(type), + (PyObject *)&_Py_SINGLETON(tuple_empty), NULL); + if (self == NULL) { + goto exit; + } + _result = _elementtree_Element___init___impl((ElementObject *)self, tag, attrib, __clinic_kwds); + if (_result != 0) { + Py_DECREF(self); + goto exit; + } + return_value = self; + +exit: + /* Cleanup for kwds */ + Py_XDECREF(__clinic_kwds); + + return return_value; +} + PyDoc_STRVAR(_elementtree_SubElement__doc__, "SubElement($module, parent, tag, attrib={}, /, **extra)\n" "--\n" @@ -1474,4 +1574,4 @@ _elementtree_XMLParser__setevents(PyObject *self, PyObject *const *args, Py_ssiz exit: return return_value; } -/*[clinic end generated code: output=d454d27e90eb399e input=a9049054013a1b77]*/ +/*[clinic end generated code: output=32ada61cc0b37829 input=a9049054013a1b77]*/