advanced programming techniques self original alist self shallow_copy shallow_copy def __enter__(self)self modified (self original[:if self shallow_copy else copy deepcopy(self original)return self modified def __exit__(selfexc_typeexc_valexc_tb)if exc_type is noneself original[:self modified shallow and deep copying when the atomiclist object is created we keep reference to the original list and note whether shallow copying is to be used (shallow copying is fine for lists of numbers or stringsbut for lists that contain lists or other collectionsshallow copying is not sufficient thenwhen the atomiclist context manager object is used in the with statement its __enter__(method is called at this point we copy the original list and return the copy so that all the changes can be made on the copy once we reach the end of the with statement' scope the __exit__(method is called if no exception occurred the exc_type ("exception type"will be none and we know that we can safely replace the original list' items with the items from the modified list (we cannot do self original self modified because that would just replace one object reference with another and would not affect the original list at all but if an exception occurredwe do nothing to the original list and the modified list is discarded the return value of __exit__(is used to indicate whether any exception that occurred should be propagated true value means that we have handled any exception and so no propagation should occur normally we always return false or something that evaluates to false in boolean context to allow any exception that occurred to propagate by not giving an explicit return valueour __exit__(returns none which evaluates to false and correctly causes any exception to propagate custom context managers are used in to ensure that socket connections and gzipped files are closedand some of the threading modules context managers are used in to ensure that mutual exclusion locks are unlocked you'll also get the chance to create more generic atomic contex manager in this exercises descriptors |descriptors are classes which provide access control for the attributes of other classes any class that implements one or more of the descriptor special