weakref list in python

后端 未结 6 1324
感情败类
感情败类 2021-02-04 05:08

I\'m in need of a list of weak references that deletes items when they die. Currently the only way I have of doing this is to keep flushing the list (removing dead references ma

6条回答
  •  粉色の甜心
    2021-02-04 05:11

    You can use WeakSet from the very same weakref module (it's actually defined elsewhere by the way, but it's imported there).

    >>> from weakref import WeakSet
    >>> s = WeakSet()
    >>> class Obj(object): pass # can't weakref simple objects
    >>> a = Obj()
    >>> s.add(a)
    >>> print len(s)
    1
    >>> del a
    >>> print len(s)
    0
    

提交回复
热议问题