@@ -13,6 +13,18 @@ module _bisect
1313
1414#include "clinic/_bisectmodule.c.h"
1515
16+ typedef struct {
17+ PyObject * str_insert ;
18+ } bisect_state ;
19+
20+ static inline bisect_state *
21+ get_bisect_state (PyObject * module )
22+ {
23+ void * state = PyModule_GetState (module );
24+ assert (state != NULL );
25+ return (bisect_state * )state ;
26+ }
27+
1628static inline Py_ssize_t
1729internal_bisect_right (PyObject * list , PyObject * item , Py_ssize_t lo , Py_ssize_t hi ,
1830 PyObject * key )
@@ -129,7 +141,8 @@ _bisect_insort_right_impl(PyObject *module, PyObject *a, PyObject *x,
129141 return NULL ;
130142 }
131143 else {
132- result = PyObject_CallMethod (a , "insert" , "nO" , index , x );
144+ bisect_state * state = get_bisect_state (module );
145+ result = _PyObject_CallMethod (a , state -> str_insert , "nO" , index , x );
133146 if (result == NULL )
134147 return NULL ;
135148 Py_DECREF (result );
@@ -255,7 +268,8 @@ _bisect_insort_left_impl(PyObject *module, PyObject *a, PyObject *x,
255268 if (PyList_Insert (a , index , x ) < 0 )
256269 return NULL ;
257270 } else {
258- result = PyObject_CallMethod (a , "insert" , "nO" , index , x );
271+ bisect_state * state = get_bisect_state (module );
272+ result = _PyObject_CallMethod (a , state -> str_insert , "nO" , index , x );
259273 if (result == NULL )
260274 return NULL ;
261275 Py_DECREF (result );
@@ -280,13 +294,45 @@ having to sort the list after each insertion. For long lists of items with\n\
280294expensive comparison operations, this can be an improvement over the more\n\
281295common approach.\n" );
282296
297+ static int
298+ bisect_clear (PyObject * module )
299+ {
300+ bisect_state * state = get_bisect_state (module );
301+ Py_CLEAR (state -> str_insert );
302+ return 0 ;
303+ }
304+
305+ static void
306+ bisect_free (void * module )
307+ {
308+ bisect_clear ((PyObject * )module );
309+ }
310+
311+ static int
312+ bisect_modexec (PyObject * m )
313+ {
314+ bisect_state * state = get_bisect_state (m );
315+ state -> str_insert = PyUnicode_InternFromString ("insert" );
316+ if (state -> str_insert == NULL ) {
317+ return -1 ;
318+ }
319+ return 0 ;
320+ }
321+
322+ static PyModuleDef_Slot bisect_slots [] = {
323+ {Py_mod_exec , bisect_modexec },
324+ {0 , NULL }
325+ };
283326
284327static struct PyModuleDef _bisectmodule = {
285328 PyModuleDef_HEAD_INIT ,
286329 .m_name = "_bisect" ,
330+ .m_size = sizeof (bisect_state ),
287331 .m_doc = module_doc ,
288332 .m_methods = bisect_methods ,
289- .m_size = 0
333+ .m_slots = bisect_slots ,
334+ .m_clear = bisect_clear ,
335+ .m_free = bisect_free ,
290336};
291337
292338PyMODINIT_FUNC
0 commit comments