Thi Duong Nguyen
Thi Duong Nguyen

Reputation: 1835

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

I have a list of 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?

Upvotes: 6

Views: 951

Answers (5)

mhyfritz
mhyfritz

Reputation: 8522

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.

Upvotes: 6

Michael Kent
Michael Kent

Reputation: 1734

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.

Upvotes: 0

Duncan
Duncan

Reputation: 95692

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.

Upvotes: 2

feathj
feathj

Reputation: 3069

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.

Upvotes: 0

Marcelo Cantos
Marcelo Cantos

Reputation: 185902

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).

Upvotes: 1

Related Questions