python dict clear只能删除一层,不能够递归删除。

时间:2023-03-09 03:24:29
python dict clear只能删除一层,不能够递归删除。
 void
PyDict_Clear(PyObject *op)
{
dictobject *mp;
dictentry *ep, *table;
int table_is_malloced;
Py_ssize_t fill;
dictentry small_copy[PyDict_MINSIZE];
#ifdef Py_DEBUG
Py_ssize_t i, n;
#endif if (!PyDict_Check(op))
return;
mp = (dictobject *)op;
#ifdef Py_DEBUG
n = mp->ma_mask + ;
i = ;
#endif table = mp->ma_table;
assert(table != NULL);
table_is_malloced = table != mp->ma_smalltable; /* This is delicate. During the process of clearing the dict,
* decrefs can cause the dict to mutate. To avoid fatal confusion
* (voice of experience), we have to make the dict empty before
* clearing the slots, and never refer to anything via mp->xxx while
* clearing.
*/
fill = mp->ma_fill;
if (table_is_malloced)
EMPTY_TO_MINSIZE(mp); else if (fill > ) {
/* It's a small table with something that needs to be cleared.
* Afraid the only safe way is to copy the dict entries into
* another small table first.
*/
memcpy(small_copy, table, sizeof(small_copy));
table = small_copy;
EMPTY_TO_MINSIZE(mp);
}
/* else it's a small table that's already empty */ /* Now we can finally clear things. If C had refcounts, we could
* assert that the refcount on table is 1 now, i.e. that this function
* has unique access to it, so decref side-effects can't alter it.
*/
for (ep = table; fill > ; ++ep) {
#ifdef Py_DEBUG
assert(i < n);
++i;
#endif
if (ep->me_key) {
--fill;
Py_DECREF(ep->me_key);
Py_XDECREF(ep->me_value);//只有这里处理了,但是如果value是一个字典,并且有其他地方引用了,那么就不能删掉了,我觉得应该递归删除
       /*i
         f(PyDict_Check(op->me_value))
          {
            PyDict_Clear(op->me_value);
          }
        else{             Py_XDECREF(ep->me_value);
          }
        */
}
#ifdef Py_DEBUG
else
assert(ep->me_value == NULL);
#endif
} if (table_is_malloced)
PyMem_DEL(table);
}