Package lxml :: Package html :: Module _dictmixin
[hide private]
[frames] | no frames]

Source Code for Module lxml.html._dictmixin

  1  """ 
  2  A backport of UserDict.DictMixin for pre-python-2.4 
  3  """ 
  4  __all__ = ['DictMixin'] 
  5   
  6  try: 
  7      from UserDict import DictMixin 
  8  except ImportError: 
9 - class DictMixin:
10 # Mixin defining all dictionary methods for classes that already have 11 # a minimum dictionary interface including getitem, setitem, delitem, 12 # and keys. Without knowledge of the subclass constructor, the mixin 13 # does not define __init__() or copy(). In addition to the four base 14 # methods, progressively more efficiency comes with defining 15 # __contains__(), __iter__(), and iteritems(). 16 17 # second level definitions support higher levels
18 - def __iter__(self):
19 for k in self.keys(): 20 yield k
21 - def has_key(self, key):
22 try: 23 value = self[key] 24 except KeyError: 25 return False 26 return True
27 - def __contains__(self, key):
28 return self.has_key(key)
29 30 # third level takes advantage of second level definitions
31 - def iteritems(self):
32 for k in self: 33 yield (k, self[k])
34 - def iterkeys(self):
35 return self.__iter__()
36 37 # fourth level uses definitions from lower levels
38 - def itervalues(self):
39 for _, v in self.iteritems(): 40 yield v
41 - def values(self):
42 return [v for _, v in self.iteritems()]
43 - def items(self):
44 return list(self.iteritems())
45 - def clear(self):
46 for key in self.keys(): 47 del self[key]
48 - def setdefault(self, key, default=None):
49 try: 50 return self[key] 51 except KeyError: 52 self[key] = default 53 return default
54 - def pop(self, key, *args):
55 if len(args) > 1: 56 raise TypeError, "pop expected at most 2 arguments, got "\ 57 + repr(1 + len(args)) 58 try: 59 value = self[key] 60 except KeyError: 61 if args: 62 return args[0] 63 raise 64 del self[key] 65 return value
66 - def popitem(self):
67 try: 68 k, v = self.iteritems().next() 69 except StopIteration: 70 raise KeyError, 'container is empty' 71 del self[k] 72 return (k, v)
73 - def update(self, other=None, **kwargs):
74 # Make progressively weaker assumptions about "other" 75 if other is None: 76 pass 77 elif hasattr(other, 'iteritems'): # iteritems saves memory and lookups 78 for k, v in other.iteritems(): 79 self[k] = v 80 elif hasattr(other, 'keys'): 81 for k in other.keys(): 82 self[k] = other[k] 83 else: 84 for k, v in other: 85 self[k] = v 86 if kwargs: 87 self.update(kwargs)
88 - def get(self, key, default=None):
89 try: 90 return self[key] 91 except KeyError: 92 return default
93 - def __repr__(self):
94 return repr(dict(self.iteritems()))
95 - def __cmp__(self, other):
96 if other is None: 97 return 1 98 if isinstance(other, DictMixin): 99 other = dict(other.iteritems()) 100 return cmp(dict(self.iteritems()), other)
101 - def __len__(self):
102 return len(self.keys())
103