source: utilitiespy/tudelft/utilities/tools/dictkeys.py

Last change on this file was 1265, checked in by wouter, 4 weeks ago

#386 Added tests and lt and eq methods to Keys.

File size: 3.0 KB
Line 
1from typing import Dict, TypeVar, Optional, Type, Generic, Any, Iterable
2from collections.abc import Set # frozenset will not work correctly if we extend typing.Set
3
4K=TypeVar('K')
5V=TypeVar('V')
6
7class Keys(Generic[K,V], Set):
8 '''
9 Keys is a Set, containing the keys of the given dict.
10 Actions on Keys are reflected directly into the dict.
11
12 An alternative to the python dict.keys() function.
13 The dict.keys() function returns a dict_keys object
14 that really is a second class citizen because it offers a very
15 small subset of the functionality of set. Eg no "pop" method.
16
17 See also collections ABC Set
18 '''
19 def __init__(self, d:Dict[K,V]):
20 self._d:Dict[K,V]=d
21
22 def __contains__(self, key:Any):
23 return key in self._d
24
25 def __len__(self):
26 return len(self._d)
27
28 def __delitem__(self, key:K):
29 '''
30 remove key from dict. May thrkw key error. See also pop
31 '''
32 del self._d[key]
33
34 def __iter__(self):
35 return iter(self._d.keys())
36
37 def __getitem__(self, key:K)->V:
38 '''
39 raises keyerror if item not there. See also get
40 '''
41 return self._d[key]
42
43 def __hash__(self):
44 return hash(frozenset(self._d.keys()))
45
46 def __repr__(self):
47 return repr(set(self._d))
48
49 def __eq__(self, other:Any):
50 return len(self) == len(other) and self.__le__(other)
51
52 def __le__(self, other:Any):
53 if not isinstance(other, Set):
54 return NotImplemented
55 if len(self) > len(other):
56 return False
57 for elem in self:
58 if elem not in other:
59 return False
60 return True
61
62
63 def get(self, key:K, default:Optional[Type]=None)->Any:
64 '''
65 @param key the key to look up
66 @param default the default value for return if key not present, defaults to None
67 @return value for given key, or default if key is not in dict
68 '''
69 return self._d.get(key, default)
70
71 def pop(self, key:K, default:Any=None)->Any:
72 '''
73 Remove given key from the dict
74 @param key the key to pop
75 @param default the value to return if key is not present.
76 @return the value for the given key.
77 If the key is not in dict, returns the default value.
78
79 override is bit poor, because original is not properly typed...
80 '''
81 return self._d.pop(key, default)
82
83 def add(self, key:K):
84 raise NotImplemented # NotSupported would be better
85
86 def difference_update(self, *items: Iterable[Any])->None:
87 for lst in items:
88 for key in lst:
89 self._d.pop(key)
90
91 def issuperset(self, otherset: Set):
92 return set(self._d.keys()).issuperset(otherset)
93
94 def remove(self, key:K):
95 del self._d[key]
96
97 def copy(self):
98 '''
99 shallow copy of the keys at this moment
100 '''
101 return set(self._d.keys())
102
103
Note: See TracBrowser for help on using the repository browser.