dictionary that discards old items

Raymond Hettinger python at rcn.com
Sun Jul 24 06:02:43 EDT 2005


[Raymond Hettinger]
> >class Cache(dict):
> >    def __init__(self, n, *args, **kwds):
> >        self.n = n
> >        self.queue = collections.deque()
> >        dict.__init__(self, *args, **kwds)


[Bengt Richter]
> Minor comment: There is a potential name collision  problem for keyword n=something,
> so what is considered best practice to avoid that? __n or such as the n arg?

One solution is to drop the *args and **kwds part of the __init__() API
for the subclass.  For a cache class, it doesn't make sense that you
would know all of the values when the instance is first created.  If
the need arises, the update() method will suffice:

class Cache(dict):
    def __init__(self, n):
        self.n = n
        dict.__init__(self)
    . . .


The __n form doesn't get name mangled so its only advantage is in being
a less likely key.


Raymond




More information about the Python-list mailing list