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?
Python has a built-in function called enumerate() . You can use it with for loops to keep track of the index of the current element.
Everything is in Python treated as an object, including variable, function, list, tuple, dictionary, set, etc. Every object belongs to its class. For example - An integer variable belongs to integer class. An object is a real-life entity.
A Python class is like an outline for creating a new object. An object is anything that you wish to manipulate or change while working through the code. Every time a class object is instantiated, which is when we declare a variable, a new object is initiated from scratch.
Python is an object oriented programming language. Almost everything in Python is an object, with its properties and methods. A Class is like an object constructor, or a "blueprint" for creating objects.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With