the with statement is used in several places in the standard library where startup or cleanup code needs to be executed for examplethe urlopen call returns an object that can be used in with statement to clean up the socket when we're done locks in the threading module can automatically release the lock when the statement has been executed most interestinglybecause the with statement can apply to any object that has the appropriate special methodswe can use it in our own frameworks for exampleremember that strings are immutablebut sometimes you need to build string from multiple parts for efficiencythis is usually done by storing the component strings in list and joining them at the end let' create simple context manager that allows us to construct sequence of characters and automatically convert it to string upon exitclass stringjoiner(list)def __enter__(self)return self def __exit__(selftypevaluetb)self result "join(selfthis code adds the two special methods required of context manager to the list class it inherits from the __enter__ method performs any required setup code (in this casethere isn' anyand then returns the object that will be assigned to the variable after as in the with statement oftenas we've done herethis is just the context manager object itself the __exit__ method accepts three arguments in normal situationthese are all given value of none howeverif an exception occurs inside the with blockthey will be set to values related to the typevalueand traceback for the exception this allows the __exit__ method to do any cleanup code that may be requiredeven if an exception occurred in our examplewe take the irresponsible path and create result string by joining the characters in the stringregardless of whether an exception was thrown while this is one of the simplest context managers we could writeand its usefulness is dubiousit does work with with statement have look at it in actionimport randomstring with stringjoiner(as joinerfor in range( )joiner append(random choice(string ascii_letters)print(joiner result