Skip to content

Commit 0f32147

Browse files
cmaloneyclaude
andcommitted
gh-87613: Use Argument Clinic vectorcall for xml.etree.ElementTree.Element
xml.etree.ElementTree.Element gains a generated vectorcall. Keys that are not strings in `**extra` now raise TypeError on a normal call, as the Python implementation already did, because vectorcall keywords must be strings; an explicit `__init__` call and subclasses still accept them. `@text_signature` keeps the documented `(tag, /, attrib={}, **extra)`: `attrib` can still be passed by keyword, which the impl pops from `extra`. Merging the keywords into the attributes now copies them with PyDict_Copy() instead of PyDict_New() plus PyDict_Update(), and pops `attrib` with `_Py_ID(attrib)` rather than creating a string per call; SubElement shares that helper. pyperf microbenchmark (PGO+LTO, run serially): | Benchmark | base | Element | |------------------------|:-------:|:---------------------:| | E('a', x='1') | 116 ns | 76.3 ns: 1.52x faster | | E('a') | 42.6 ns | 28.2 ns: 1.51x faster | | E('a', attrib=d) | 122 ns | 82.8 ns: 1.47x faster | | E('a', d) | 73.8 ns | 53.6 ns: 1.38x faster | | SE(E('p'), 'a', x='1') | 161 ns | 120 ns: 1.35x faster | | E('a', d, y='2') | 102 ns | 80.3 ns: 1.27x faster | | S('a') | 49.4 ns | 39.8 ns: 1.24x faster | Benchmark code: ```python import pyperf runner = pyperf.Runner() setup = ("from _elementtree import Element as E, SubElement as SE\n" "d = {'x': '1'}\n" "class S(E): pass") for stmt in ["E('a')", "E('a', d)", "E('a', x='1')", "E('a', d, y='2')", "E('a', attrib=d)", "S('a')", "SE(E('p'), 'a', x='1')"]: runner.timeit(stmt, stmt, setup) ``` Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 0461451 commit 0f32147

8 files changed

Lines changed: 161 additions & 50 deletions

‎Include/internal/pycore_global_objects_fini_generated.h‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎Include/internal/pycore_global_strings.h‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -327,6 +327,7 @@ struct _Py_global_strings {
327327
STRUCT_FOR_ID(ast)
328328
STRUCT_FOR_ID(athrow)
329329
STRUCT_FOR_ID(attr)
330+
STRUCT_FOR_ID(attrib)
330331
STRUCT_FOR_ID(attribute)
331332
STRUCT_FOR_ID(autocommit)
332333
STRUCT_FOR_ID(backtick)

‎Include/internal/pycore_runtime_init_generated.h‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎Include/internal/pycore_unicodeobject_generated.h‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎Lib/test/test_xml_etree.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3022,6 +3022,10 @@ def f():
30223022

30233023
class BasicElementTest(ElementTestCase, unittest.TestCase):
30243024

3025+
def test_extra_keys_must_be_strings(self):
3026+
with self.assertRaisesRegex(TypeError, "keywords must be strings"):
3027+
ET.Element("tag", **{ET.QName("key"): "value"})
3028+
30253029
def test___init__(self):
30263030
tag = "foo"
30273031
attrib = { "zix": "wyp" }
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Calling :class:`xml.etree.ElementTree.Element` with non-string keys in
2+
*extra* now raises :exc:`TypeError`, as the Python implementation already
3+
did. Pass such keys in *attrib* instead.

‎Modules/_elementtree.c‎

Lines changed: 48 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
#include "pycore_ceval.h" // _Py_EnterRecursiveCall()
2020
#include "pycore_dict.h" // _PyDict_CopyAsDict()
2121
#include "pycore_pyhash.h" // _Py_HashSecret
22+
#include "pycore_runtime.h" // _Py_ID()
2223
#include "pycore_tuple.h" // _PyTuple_FromPair
2324
#include "pycore_weakref.h" // FT_CLEAR_WEAKREFS()
2425

@@ -377,7 +378,7 @@ static PyObject*
377378
get_attrib_from_keywords(PyObject *kwds)
378379
{
379380
PyObject *attrib;
380-
if (PyDict_PopString(kwds, "attrib", &attrib) < 0) {
381+
if (PyDict_Pop(kwds, &_Py_ID(attrib), &attrib) < 0) {
381382
return NULL;
382383
}
383384

@@ -393,16 +394,13 @@ get_attrib_from_keywords(PyObject *kwds)
393394
return NULL;
394395
}
395396
Py_SETREF(attrib, _PyDict_CopyAsDict(attrib));
397+
if (attrib != NULL && PyDict_Update(attrib, kwds) < 0) {
398+
Py_DECREF(attrib);
399+
return NULL;
400+
}
401+
return attrib;
396402
}
397-
else {
398-
attrib = PyDict_New();
399-
}
400-
401-
if (attrib != NULL && PyDict_Update(attrib, kwds) < 0) {
402-
Py_DECREF(attrib);
403-
return NULL;
404-
}
405-
return attrib;
403+
return PyDict_Copy(kwds);
406404
}
407405

408406
/*[clinic input]
@@ -413,15 +411,37 @@ class _elementtree.XMLParser "XMLParserObject *" "clinic_state()->XMLParser_Type
413411
[clinic start generated code]*/
414412
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=6c83ea832d2b0ef1]*/
415413

414+
/*[clinic input]
415+
@vectorcall
416+
@text_signature "(tag, /, attrib={}, **extra)"
417+
_elementtree.Element.__init__
418+
419+
tag: object
420+
attrib: object(c_default="NULL") = {}
421+
/
422+
**extra: dict
423+
424+
An XML element.
425+
426+
This class is the reference implementation of the Element interface.
427+
428+
An element's length is its number of subelements. That means if you
429+
want to check if an element is truly empty, you should check BOTH
430+
its length AND its text attribute.
431+
432+
*tag* is the element name. *attrib* is an optional dictionary
433+
containing element attributes. *extra* are additional element
434+
attributes given as keyword arguments.
435+
436+
Example form:
437+
<tag attrib>text<child/>...</tag>tail
438+
[clinic start generated code]*/
439+
416440
static int
417-
element_init(PyObject *self, PyObject *args, PyObject *kwds)
441+
_elementtree_Element___init___impl(ElementObject *self, PyObject *tag,
442+
PyObject *attrib, PyObject *extra)
443+
/*[clinic end generated code: output=d10be095275d5d1a input=a66a3eacbc30aa64]*/
418444
{
419-
PyObject *tag;
420-
PyObject *attrib = NULL;
421-
ElementObject *self_elem;
422-
423-
if (!PyArg_ParseTuple(args, "O|O:Element", &tag, &attrib))
424-
return -1;
425445
if (attrib != NULL && !PyAnyDict_Check(attrib)) {
426446
PyErr_Format(PyExc_TypeError,
427447
"Element() argument 2 must be dict or frozendict, not %T",
@@ -434,23 +454,21 @@ element_init(PyObject *self, PyObject *args, PyObject *kwds)
434454
attrib = _PyDict_CopyAsDict(attrib);
435455
if (!attrib)
436456
return -1;
437-
if (kwds) {
438-
if (PyDict_Update(attrib, kwds) < 0) {
457+
if (extra) {
458+
if (PyDict_Update(attrib, extra) < 0) {
439459
Py_DECREF(attrib);
440460
return -1;
441461
}
442462
}
443-
} else if (kwds) {
463+
} else if (extra) {
444464
/* have keywords args */
445-
attrib = get_attrib_from_keywords(kwds);
465+
attrib = get_attrib_from_keywords(extra);
446466
if (!attrib)
447467
return -1;
448468
}
449469

450-
self_elem = (ElementObject *)self;
451-
452470
if (attrib != NULL && !is_empty_dict(attrib)) {
453-
if (create_extra(self_elem, attrib) < 0) {
471+
if (create_extra(self, attrib) < 0) {
454472
Py_DECREF(attrib);
455473
return -1;
456474
}
@@ -460,10 +478,10 @@ element_init(PyObject *self, PyObject *args, PyObject *kwds)
460478
Py_XDECREF(attrib);
461479

462480
/* Replace the objects already pointed to by tag, text and tail. */
463-
Py_XSETREF(self_elem->tag, Py_NewRef(tag));
481+
Py_XSETREF(self->tag, Py_NewRef(tag));
464482

465-
_set_joined_ptr(&self_elem->text, Py_NewRef(Py_None));
466-
_set_joined_ptr(&self_elem->tail, Py_NewRef(Py_None));
483+
_set_joined_ptr(&self->text, Py_NewRef(Py_None));
484+
_set_joined_ptr(&self->tail, Py_NewRef(Py_None));
467485

468486
return 0;
469487
}
@@ -4451,27 +4469,8 @@ static PyGetSetDef element_getsetlist[] = {
44514469
{NULL},
44524470
};
44534471

4454-
PyDoc_STRVAR(element_doc,
4455-
"Element(tag, attrib={}, **extra)\n"
4456-
"--\n"
4457-
"\n"
4458-
"An XML element.\n"
4459-
"\n"
4460-
"This class is the reference implementation of the Element interface.\n"
4461-
"\n"
4462-
"An element's length is its number of subelements. That means if you\n"
4463-
"want to check if an element is truly empty, you should check BOTH\n"
4464-
"its length AND its text attribute.\n"
4465-
"\n"
4466-
"*tag* is the element name. *attrib* is an optional dictionary\n"
4467-
"containing element attributes. *extra* are additional element\n"
4468-
"attributes given as keyword arguments.\n"
4469-
"\n"
4470-
"Example form:\n"
4471-
" <tag attrib>text<child/>...</tag>tail");
4472-
44734472
static PyType_Slot element_slots[] = {
4474-
{Py_tp_doc, (void *)element_doc},
4473+
{Py_tp_doc, (void *)_elementtree_Element___init____doc__},
44754474
{Py_tp_dealloc, element_dealloc},
44764475
{Py_tp_repr, element_repr},
44774476
{Py_tp_getattro, PyObject_GenericGetAttr},
@@ -4480,7 +4479,8 @@ static PyType_Slot element_slots[] = {
44804479
{Py_tp_methods, element_methods},
44814480
{Py_tp_members, element_members},
44824481
{Py_tp_getset, element_getsetlist},
4483-
{Py_tp_init, element_init},
4482+
{Py_tp_init, _elementtree_Element___init__},
4483+
{Py_tp_vectorcall, _elementtree_Element_vectorcall},
44844484
{Py_tp_alloc, PyType_GenericAlloc},
44854485
{Py_tp_new, element_new},
44864486
{Py_sq_length, element_length},

‎Modules/clinic/_elementtree.c.h‎

Lines changed: 102 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)