more obvious alternative would have been self __key key if key is not none else _identity once we have the key functionwe use an assert to ensure that it is callable the built-in hasattr(function returns true if the object passed as its first argument has the attribute whose name is passed as its second argument there are corresponding setattr(and delattr(functions--these functions are covered in all callable objectsfor examplefunctions and methodshave __call__ attribute to make the creation of sortedlists as similar as possible to the creation of lists we have an optional sequence argument that corresponds to the single optional argument that list(accepts the sortedlist class aggregates list collection in the private variable self __list and keeps the items in the aggregated list in sorted order using the given key function the elif clause uses type testing to see whether the given sequence is sortedlist and if that is the case whether it has the same key function as this sorted list if these conditions are met we simply shallow-copy the sequence' list without needing to sort it if most key functions are created on the fly using lambdaeven though two may have the same code they will not compare as equalso the efficiency gain may not be realized in practice @property def key(self)return self __key once sorted list is created its key function is fixedso we keep it as private variable to prevent users from changing it but some users may want to get reference to the key function (as we will see in the next subsection)and so we have made it accessible by providing the read-only key property def add(selfvalue)index self __bisect_left(valueif index =len(self __list)self __list append(valueelseself __list insert(indexvaluewhen this method is called the given value must be inserted into the private self __list in the correct position to preserve the list' order the private sortedlist __bisect_left(method returns the required index position as we will see in moment if the new value is larger than any other value in the list it must go at the endso the index position will be equal to the list' length (list index positions go from to len( )--if this is the case we append the new value otherwisewe insert the new value at the given index position--which will be at index position if the new value is smaller than any other value in the list