Storage for store information about domains determined by key prefixes. See the docsting for details.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | class PrefixStorage(object):
"""Storage for store information about prefixes.
>>> s = PrefixStorage()
First we save information for some prefixes:
>>> s["123"] = "123 domain"
>>> s["12"] = "12 domain"
Then we can retrieve prefix information by full key
(longest prefix always win):
>>> s.getByPrefix("123456")
'123 domain'
>>> s.getByPrefix("12456")
'12 domain'
If no prefix has been found then getByPrefix() returns default value:
>>> s.getByPrefix("13456", "None")
'None'
"""
def __init__(self):
self._mapping = {}
self._sizes = []
def __setitem__(self, key, value):
ln = len(key)
if ln not in self._sizes:
self._sizes.append(ln)
self._sizes.sort()
self._sizes.reverse()
self._mapping[key] = value
def getByPrefix(self, key, default=None):
for ln in self._sizes:
k = key[:ln]
if k in self._mapping:
return self._mapping[k]
return default
|
Tags: algorithms
subclass dict. PrefixStorage is ultimately a kind of dict, so it should subclass dict. By overriding the get, __getitem__ and __setitem__ methods one could create a drop-in-replacement, so that:
'1234Server'
just an algorithm example. If you want PrefixStorage subclass dict then it should override most of dict methods for maintaining self._sizes. Better way is to subclass UserDict.DictMixin. But I think you should always distinguish get/__getitem__ and getByPrefix, so:
but
BTW someone may set self._mapping on some persistent dict-like object.