Lazy container
Peter Otten
__peter__ at web.de
Tue Feb 13 08:31:03 EST 2007
Cristiano Paris wrote:
> I'm trying to write a Container which should mimic a list. Basically,
> the container pulls items on the fly from an unspecified source through
> a function and returns an instance of a given class over the pulled item.
>
> That is:
>
> class lazy(object):
> def __getitem__(self,index):
> return Foo(f(index))
>
> lc = lazy()
>
> Here I see a problem: two consecutive accesses to lc for the same index
> would retrieve two different instances of Foo.
>
> In some scenarios this is not desirable since one wants to have all the
> accessors to share the same instance for the same index so as to reduce
> memory consumption.
>
> So, I thought to use an internal dictionary of all the Foo instances
> given away so far. Something like:
> The problem with this implementation is that the cache never decreases
> in length as Foo instances are no longer referenced by the lc accessor
> since they're all referenced by the internal cache.
You want a WeakValueDictionary:
http://docs.python.org/lib/module-weakref.html
Peter
More information about the Python-list
mailing list