Вы можете расширить dict по умолчанию и использовать метод __missing__
для вызова функции загрузки, если ключ отсутствует:
class ImageDict(dict):
def __missing__(self, key):
self[key] = img = self.load(key)
return img
def load(self, key):
# create a queue if not exist (could be moved to __init__)
if not hasattr(self, '_queue'):
self._queue = []
# pop the oldest entry in the list and the dict
if len(self._queue) >= 100:
self.pop(self._queue.pop(0))
# append this key as a newest entry in the queue
self._queue.append(key)
# implement image loading here and return the image instance
print 'loading', key
return 'Image for %s' % key
И вывод (загрузка происходит только тогда, когда ключ не существуетпока что.)
>>> d = ImageDict()
>>> d[3]
loading 3
'Image for 3'
>>> d[3]
'Image for 3'
>>> d['bleh']
loading bleh
'Image for bleh'
>>> d['bleh']
'Image for bleh'
Одна эволюция состояла бы в том, чтобы сохранить только последний N элемент в dict и очистить самые старые записи.Вы можете реализовать это, сохранив список ключей для заказа.