Coverage for /usr/lib/python3/dist-packages/fontTools/misc/dictTools.py: 50%

26 statements  

« prev     ^ index     » next       coverage.py v7.9.1, created at 2025-06-14 15:55 +0200

1"""Misc dict tools.""" 

2 

3 

4__all__ = ["hashdict"] 

5 

6 

7# https://stackoverflow.com/questions/1151658/python-hashable-dicts 

8class hashdict(dict): 

9 """ 

10 hashable dict implementation, suitable for use as a key into 

11 other dicts. 

12 

13 >>> h1 = hashdict({"apples": 1, "bananas":2}) 

14 >>> h2 = hashdict({"bananas": 3, "mangoes": 5}) 

15 >>> h1+h2 

16 hashdict(apples=1, bananas=3, mangoes=5) 

17 >>> d1 = {} 

18 >>> d1[h1] = "salad" 

19 >>> d1[h1] 

20 'salad' 

21 >>> d1[h2] 

22 Traceback (most recent call last): 

23 ... 

24 KeyError: hashdict(bananas=3, mangoes=5) 

25 

26 based on answers from 

27 http://stackoverflow.com/questions/1151658/python-hashable-dicts 

28 

29 """ 

30 

31 def __key(self): 

32 return tuple(sorted(self.items())) 

33 

34 def __repr__(self): 

35 return "{0}({1})".format( 

36 self.__class__.__name__, 

37 ", ".join("{0}={1}".format(str(i[0]), repr(i[1])) for i in self.__key()), 

38 ) 

39 

40 def __hash__(self): 

41 return hash(self.__key()) 

42 

43 def __setitem__(self, key, value): 

44 raise TypeError( 

45 "{0} does not support item assignment".format(self.__class__.__name__) 

46 ) 

47 

48 def __delitem__(self, key): 

49 raise TypeError( 

50 "{0} does not support item assignment".format(self.__class__.__name__) 

51 ) 

52 

53 def clear(self): 

54 raise TypeError( 

55 "{0} does not support item assignment".format(self.__class__.__name__) 

56 ) 

57 

58 def pop(self, *args, **kwargs): 

59 raise TypeError( 

60 "{0} does not support item assignment".format(self.__class__.__name__) 

61 ) 

62 

63 def popitem(self, *args, **kwargs): 

64 raise TypeError( 

65 "{0} does not support item assignment".format(self.__class__.__name__) 

66 ) 

67 

68 def setdefault(self, *args, **kwargs): 

69 raise TypeError( 

70 "{0} does not support item assignment".format(self.__class__.__name__) 

71 ) 

72 

73 def update(self, *args, **kwargs): 

74 raise TypeError( 

75 "{0} does not support item assignment".format(self.__class__.__name__) 

76 ) 

77 

78 # update is not ok because it mutates the object 

79 # __add__ is ok because it creates a new object 

80 # while the new object is under construction, it's ok to mutate it 

81 def __add__(self, right): 

82 result = hashdict(self) 

83 dict.update(result, right) 

84 return result