Set class with timed auto remove of elements

前端 未结 2 1294
故里飘歌
故里飘歌 2021-01-14 09:15

I\'m writing a software with Python and I need a class to store a set of elements (order is not relevant and not repeated elements), like the Python class set,

2条回答
  •  孤街浪徒
    2021-01-14 09:51

    I don't see any reason not to go with multithreading. As it is really easy to implement, with minimum code. Roughly something like this:

    import threading
    import time
    
    def ttl_set_remove(my_set, item, ttl):
        time.sleep(ttl)
        my_set.remove(item)
    
    class MySet(set):
        def add(self, item, ttl):
            set.add(self, item)
            t = threading.Thread(target=ttl_set_remove, args=(self, item, ttl))
            t.start()
    

    test:

    s = MySet()
    s.add('a', 20)
    s.add('b', 10)
    s.add('c', 2)
    
    print(s)
    time.sleep(5)
    print(s)
    
    >>> 
    MySet({'c', 'b', 'a'})
    MySet({'b', 'a'})
    

提交回复
热议问题