protocoland so can be used with the with statement for examplefile objects (covered in have context manager that automatically closes the file after the with block regardless of whether an exception is raisedand regardless of if or when the version of python running the code may close automaticallywith open( ' :\misc\data'as myfilefor line in myfileprint(linemore code here herethe call to open returns simple file object that is assigned to the name myfile we can use myfile with the usual file tools--in this casethe file iterator reads line by line in the for loop howeverthis object also supports the context management protocol used by the with statement after this with statement has runthe context management machinery guarantees that the file object referenced by myfile is automatically closedeven if the for loop raised an exception while processing the file although file objects may be automatically closed on garbage collectionit' not always straightforward to know when that will occurespecially when using alternative python implementations the with statement in this role is an alternative that allows us to be sure that the close will occur after execution of specific block of code as we saw earlierwe can achieve similar effect with the more general and explicit try/finally statementbut it requires three more lines of administrative code in this case (four instead of just one)myfile open( ' :\misc\data'tryfor line in myfileprint(linemore code here finallymyfile close(we won' cover python' multithreading modules in this book (for more on that topicsee follow-up application-level texts such as programming pythonbut the lock and condition synchronization objects they define may also be used with the with statementbecause they support the context management protocol--in this case adding both entry and exit actions around blocklock threading lock(with lockcritical section of code access shared resources afterimport threading herethe context management machinery guarantees that the lock is automatically acquired before the block is executed and released once the block is completeregardless of exception outcomes with/as context managers