1、说明
从internedictionary的所有字符串中清除函数,调整这些对象的引用计数,并将其标记为NOT_INTERNED,这样垃圾就可以回收了。当所有字符串标记为NOT_INTERNED时,清空并删除interned字典。
2、清理实例
这个清理函数是_PyUnicode_ClearInterned,在 unicodeobject.c 中定义。
void _PyUnicode_ClearInterned(PyThreadState*tstate) { ... //Getallthekeystotheinterneddictionary PyObject*keys=PyDict_Keys(interned); ... //InternedUnicodestringsarenotforciblydeallocated; //rather,wegivethemtheirstolenreferencesback //andthenclearandDECREFtheinterneddict. for(Py_ssize_ti=0;i<n;i++){ PyObject*s=PyList_GET_ITEM(keys,i); ... switch(PyUnicode_CHECK_INTERNED(s)){ caseSSTATE_INTERNED_IMMORTAL: Py_SET_REFCNT(s,Py_REFCNT(s)+1); break; caseSSTATE_INTERNED_MORTAL: //Restorethetworeferences(keyandvalue)ignored //byPyUnicode_InternInPlace(). Py_SET_REFCNT(s,Py_REFCNT(s)+2); break; caseSSTATE_NOT_INTERNED: /*fallthrough*/ default: Py_UNREACHABLE(); } //markingthestringtobeNOT_INTERNED _PyUnicode_STATE(s).interned=SSTATE_NOT_INTERNED; } //decreasingthereferencetotheinitializedand //accesskeysobject. Py_DECREF(keys); //clearingthedictionary PyDict_Clear(interned); //clearingtheobjectinterned Py_CLEAR(interned); }
以上是Python清理驻留字符串的方法,希望对大家有所帮助。助。更多Python学习指导:python基础教程