April 2019
Intermediate to advanced
646 pages
16h 48m
English
The try...finally statement is useful to ensure some cleanup code is run, even if an error is raised. There are many use cases for this, such as the following:
The with statement factors out these use cases by providing a simple way to wrap a block of code with methods defined within the context manager. This allows us to call some code before and after block execution, even if this block raises an exception. For example, working with a file is often done like so:
>>> hosts = open('/etc/hosts')
>>> try:
... for line in hosts:
... if line.startswith('#'):
... continue
... print(line.strip()) ...