@@ -98,6 +98,7 @@ typedef struct {
98
98
PyTypeObject * TreeBuilder_Type ;
99
99
PyTypeObject * XMLParser_Type ;
100
100
101
+ PyObject * expat_capsule ;
101
102
struct PyExpat_CAPI * expat_capi ;
102
103
} elementtreestate ;
103
104
@@ -155,6 +156,7 @@ elementtree_clear(PyObject *m)
155
156
Py_CLEAR (st -> ElementIter_Type );
156
157
Py_CLEAR (st -> TreeBuilder_Type );
157
158
Py_CLEAR (st -> XMLParser_Type );
159
+ Py_CLEAR (st -> expat_capsule );
158
160
159
161
st -> expat_capi = NULL ;
160
162
return 0 ;
@@ -175,6 +177,7 @@ elementtree_traverse(PyObject *m, visitproc visit, void *arg)
175
177
Py_VISIT (st -> ElementIter_Type );
176
178
Py_VISIT (st -> TreeBuilder_Type );
177
179
Py_VISIT (st -> XMLParser_Type );
180
+ Py_VISIT (st -> expat_capsule );
178
181
return 0 ;
179
182
}
180
183
@@ -3066,6 +3069,7 @@ typedef struct {
3066
3069
PyObject * handle_close ;
3067
3070
3068
3071
elementtreestate * state ;
3072
+ PyObject * elementtree_module ;
3069
3073
} XMLParserObject ;
3070
3074
3071
3075
/* helpers */
@@ -3607,7 +3611,11 @@ xmlparser_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3607
3611
self -> handle_start = self -> handle_data = self -> handle_end = NULL ;
3608
3612
self -> handle_comment = self -> handle_pi = self -> handle_close = NULL ;
3609
3613
self -> handle_doctype = NULL ;
3610
- self -> state = get_elementtree_state_by_type (type );
3614
+ self -> elementtree_module = PyType_GetModuleByDef (type , & elementtreemodule );
3615
+ assert (self -> elementtree_module != NULL );
3616
+ Py_INCREF (self -> elementtree_module );
3617
+ // See gh-111784 for explanation why is reference to module needed here.
3618
+ self -> state = get_elementtree_state (self -> elementtree_module );
3611
3619
}
3612
3620
return (PyObject * )self ;
3613
3621
}
@@ -3784,6 +3792,7 @@ xmlparser_gc_clear(XMLParserObject *self)
3784
3792
EXPAT (st , ParserFree )(parser );
3785
3793
}
3786
3794
3795
+ Py_CLEAR (self -> elementtree_module );
3787
3796
Py_CLEAR (self -> handle_close );
3788
3797
Py_CLEAR (self -> handle_pi );
3789
3798
Py_CLEAR (self -> handle_comment );
@@ -4343,7 +4352,10 @@ module_exec(PyObject *m)
4343
4352
goto error ;
4344
4353
4345
4354
/* link against pyexpat */
4346
- st -> expat_capi = PyCapsule_Import (PyExpat_CAPSULE_NAME , 0 );
4355
+ if (!(st -> expat_capsule = _PyImport_GetModuleAttrString ("pyexpat" , "expat_CAPI" )))
4356
+ goto error ;
4357
+ if (!(st -> expat_capi = PyCapsule_GetPointer (st -> expat_capsule , PyExpat_CAPSULE_NAME )))
4358
+ goto error ;
4347
4359
if (st -> expat_capi ) {
4348
4360
/* check that it's usable */
4349
4361
if (strcmp (st -> expat_capi -> magic , PyExpat_CAPI_MAGIC ) != 0 ||
0 commit comments