开发者

What's the most elegant way of keeping track of the last time a python object is accessed?

I have a list o开发者_如何学Gof objects in python that I would regularly check and destroy some of them - those which haven't been accessed lately (i.e. no method was called).

I can maintain the last time accessed and update it in every method, but is there any more elegant way to achieve this?


Use a decorator for the methods you want wrapped with the timestamp functionality, as @Marcelo Cantos pointed out.

Consider this example:

from datetime import datetime
import time
import functools

def t_access(method):
    @functools.wraps(method)
    def wrapper(self):
        self.timestamp = datetime.now()
        method(self)
    return wrapper

class Foo(object):
    @t_access
    def bar(self):
        print "method bar() called"

f = Foo()
f.bar()
print f.timestamp
time.sleep(5)
f.bar()
print f.timestamp

Edit: added functools.wraps as pointed out by @Peter Milley.


If you are using python 3.2 then have a look at functions.lru_cache() and see if that does what you want. It won't give you a last modified time, but it will do the cleanup of unused object.

For older versions it might provide the pattern you want to use but you'll have to provide the code.


Python's highly dynamic nature lets you write proxies that wrap objects in interesting ways. In this case, you could write a proxy that replaces the methods of an object (or an entire class) with wrapper methods that update a timestamp and then delegates the call to the original method.

This is somewhat involved. A simpler mechanism is to use Python decorators to augment specific methods. This also lets you exempt some functions that don't constitute an "access" when they are called (if you need this).


What is the scope of your objects? Can you lock down where they are stored and accessed? If so, you should consider creating some kind of special container that will timestamp when the object was last used or accessed. Access to the objects would be tightly controlled by a function which could time-stamp last access time.


Keep a dict of the IMAP connections, keyed by the user ID. Write a function, that given a user ID, returns an IMAP connection. The function will look up the user ID in the dict, and if the user ID is there, get the corresponding IMAP connection, and check that it's still alive. If alive, the function returns that connection. If not alive, or if the user ID was not in the dict, it creates a new connection, adds it to the dict, and returns the new connection. No timestamps required.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜