There is a trick to get around this if you need to, but use it at your own risk: You can wrap a mutable structure inside a class instance which has both a __eq__() and a __hash__() method. You must then make sure that the hash value for all such wrapper objects that reside in a dictionary (or other hash based structure), remain fixed while the object is in the dictionary (or other structure). 

classListWrapper : def __init__ (self, the_list): self.the_list =the_list def __eq__ (self, other): return self.the_list ==other .the_list def __hash__ (self): l =self.the_list result=98767 -len(l) *555 for i, el in enumerate(l): try : result=result+(hash (el)%9999999 )*1001 +i except Exception: result=(result%7777777 )+i *333 return result 

Note that the hash computation is complicated by the possibility that some members of the list may be unhashable and also by the possibility of arithmetic overflow. 

Furthermore it must always be the case that if$_{o1 == o2}$ (ie$_{o1.__eq__(o2) is True}$ ) then$_{hash(o1) ==}$ hash(o2) (ie,$_{o1.__hash__() == o2.__hash__()}$ ), regardless of whether the object is in a dictionary or not. If you fail to meet these restrictions dictionaries and other hash based structures will misbehave. 

In the case of ListWrapper, whenever the wrapper object is in a dictionary the wrapped list must not change to avoid anomalies. Don’t do this unless you are prepared to think hard about the requirements and the consequences of not meeting them correctly. Consider yourself warned. 

## 3.21 Why doesn’t list.sort() return the sorted list? 

In situations where performance matters, making a copy of the list just to sort it would be wasteful. Therefore, list.sort() sorts the list in place. In order to remind you of that fact, it does not return the sorted list. This way, you won’t be fooled into accidentally overwriting a list when you need a sorted copy but also need to keep the unsorted version around. 

If you want to return a new list, use the built-in$_{sorted()}$ function instead. This function creates a new list from a provided iterable, sorts it and returns it. For example, here’s how to iterate over the keys of a dictionary in sorted order: 

for key in sorted(mydict): ... # do whatever with mydict[key]... 

## 3.22 How do you specify and enforce an interface spec in Python? 

An interface specification for a module as provided by languages such as C++ and Java describes the prototypes for the methods and functions of the module. Many feel that compile-time enforcement of interface specifications helps in the construction of large programs. 

Python 2.6 adds an $_{abc}$module that lets you define Abstract Base Classes (ABCs). You can then use isinstance() and$_{issubclass()}$ to check whether an instance or a class implements a particular ABC. The collections.abc module defines a set of useful ABCs such as $_{Iterable}$, $_{Container}$, and $_{MutableMapping}$. 

