Alex Rivera | Logout

Automatically expiring variable

Asked 2010-10-13T19:13:59.227
10

How to implement an automatically expiring variable in python? For example, Let the program running For one hour. I want implement an array of 6 variables, each variable in array will be automatically deleted themselves after 10 mins. And after 1 hour, there will be no variable in the array.

Edit
Report

1 Answer

3

you can create a background process that check how much time it's passed, and del the right item... or if you want to create a subclass of list wich deletes it's contens after a certain time you can do the same thing, just calling it in init

def __init__(self, time):
    #run subprocess to chek_espired elements

edit:

i wrote an example, but it can be done much better!

class MyList(list):
    def __init__(self,elems,  expires_time):
        list.__init__(self, elems)
        self.created = time.time()
        self.expires_time = expires_time
    def __getitem__(self, index):
        t = time.time()
        print t -  self.created
        if t - self.created > self.expires_time:
            self.created += self.expires_time
            self.pop(index)
            self.__getitem__(index)
        return list.__getitem__(self, index)

ps of course you can easily raise a personal error if the program try to get the index from an empty list

answered 2010-10-13T19:47:46.447

Your Answer