weakref list in python

后端 未结 6 1333
感情败类
感情败类 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:30

    How do you plan on using B? The only thing I ever do with the weakref list I built is iterate over it, so its implementation is simple:

    import weakref
    
    class WeakRefList(object):
        "weakref psuedo list"
        def __init__(yo):
            yo._items = list()
        def __iter__(yo):
            yo._items = [s for s in yo._items if s() is not None]
            return (s() for s in yo._items if s() is not None)
        def __len__(yo):
            yo._items = [s for s in yo._items if s() is not None]
            return len(yo._items)
        def append(yo, new_item):
            yo._items.append(weakref.ref(new_item))
            yo._items = [s for s in yo._items if s() is not None]
    

提交回复
热议问题