Skip to Content
Expert Python Programming - Third Edition
book

Expert Python Programming - Third Edition

by Michał Jaworski, Tarek Ziadé, Cody Jackson
April 2019
Intermediate to advanced
646 pages
16h 48m
English
Packt Publishing
Content preview from Expert Python Programming - Third Edition

Context managers – the with statement

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:

  • Closing a file
  • Releasing a lock
  • Making a temporary code patch
  • Running protected code in a special environment

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()) ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Expert Python Programming - Fourth Edition

Expert Python Programming - Fourth Edition

Michał Jaworski, Tarek Ziade, Tarek Ziadé

Publisher Resources

ISBN: 9781789808896Other