Added InsensitivePreservingDict and made IrcDict a subclass of it.

This commit is contained in:
Jeremy Fincher 2004-02-05 07:14:35 +00:00
parent 0d2724d0f3
commit 6771c24ca6
3 changed files with 34 additions and 30 deletions

View File

@ -381,36 +381,10 @@ class IrcString(str):
return hash(self.lowered)
class IrcDict(dict):
class IrcDict(utils.InsensitivePreservingDict):
"""Subclass of dict to make key comparison IRC-case insensitive."""
def __init__(self, *args, **kwargs):
self.__parent = super(IrcDict, self)
self.__parent.__init__(*args, **kwargs)
def __contains__(self, s):
return self.__parent.__contains__(IrcString(s))
has_key = __contains__
key = staticmethod(toLower)
def __setitem__(self, s, v):
self.__parent.__setitem__(IrcString(s), v)
def __getitem__(self, s):
return self.__parent.__getitem__(IrcString(s))
def __delitem__(self, s):
self.__parent.__delitem__(IrcString(s))
def __repr__(self):
return '%s(%s)' % (self.__class__.__name__, self.__parent.__repr__())
def __reduce__(self):
return (self.__class__, (dict(self),))
def setdefault(self, s, v):
return self.__parent.setdefault(IrcString(s), v)
def get(self, s, d=None):
return self.__parent.get(IrcString(s), d)
class IrcSet(sets.Set):
"""A sets.Set using IrcStrings instead of regular strings."""

View File

@ -33,8 +33,6 @@
Simple utility functions.
"""
## from __future__ import generators
__revision__ = "$Id$"
import fix
@ -49,6 +47,7 @@ import string
import sgmllib
import compiler
import textwrap
import UserDict
import htmlentitydefs
from itertools import imap, ifilter
@ -583,6 +582,32 @@ def isIPV6(s):
return True
return False
class InsensitivePreservingDict(UserDict.DictMixin, object):
key = staticmethod(str.lower)
def __init__(self, dict=None, key=None):
if key is not None:
self.key = key
self.data = {}
if dict is not None:
self.update(dict)
def __getitem__(self, k):
return self.data[self.key(k)][1]
def __setitem__(self, k, v):
self.data[self.key(k)] = (k, v)
def __delitem__(self, k):
del self.data[self.key(k)]
def iteritems(self):
for t in self.data.itervalues():
yield t
def __reduce__(self):
return (self.__class__, (dict(self.data.values()),))
if __name__ == '__main__':
import sys, doctest
doctest.testmod(sys.modules['__main__'])

View File

@ -345,6 +345,11 @@ class UtilsTest(unittest.TestCase):
self.failUnless(f('2001::'))
self.failUnless(f('2001:888:0:1::666'))
def testInsensitivePreservingDict(self):
ipd = utils.InsensitivePreservingDict
d = ipd(dict(Foo=10))
self.failUnless(d['foo'] == 10)
# vim:set shiftwidth=4 tabstop=8 expandtab textwidth=78: