it is only necessary to use contextlib nested(for python from python this function is deprecated because python can handle multiple context managers in single with statement here is the same example--again omitting irrelevant lines--but this time for python trywith open(sourceas finopen(target" "as foutfor line in finusing this syntax keeps context managers and the variables they are associated with togethermaking the with statement much more readable than if we were to nest them or to use contextlib nested(it isn' only file objects that are context managers for exampleseveral threading-related classes used for locking are context managers context managers can also be used with decimal decimal numbersthis is useful if we want to perform some calculations with certain settings (such as particular precisionin effect if we want to create custom context manager we must create class that provides two methods__enter__(and __exit__(whenever with statement is used on an instance of such classthe __enter__(method is called and the return value is used for the as variable (or thrown away if there isn' onewhen control leaves the scope of the with statement the __exit__(method is called (with details of an exception if one has occurred passed as argumentssuppose we want to perform several operations on list in an atomic manner--that iswe either want all the operations to be done or none of them so that the resultant list is always in known state for exampleif we have list of integers and want to append an integerdelete an integerand change couple of integersall as single operationwe could write code like thistrywith atomiclist(itemsas atomicatomic append( del atomic[ atomic[ atomic[index except (attributeerrorindexerrorvalueerroras errprint("no changes applied:"errif no exception occursall the operations are applied to the original list (items)but if an exception occursno changes are made at all here is the code for the atomiclist context managerclass atomiclistdef __init__(selfalistshallow_copy=true)threading