Skip to Content
Fluent Python
book

Fluent Python

by Luciano Ramalho
August 2015
Intermediate
790 pages
18h 48m
English
O'Reilly Media, Inc.
Content preview from Fluent Python

Chapter 15. Context Managers and else Blocks

Context managers may end up being almost as important as the subroutine itself. We’ve only scratched the surface with them. […] Basic has a with statement, there are with statements in lots of languages. But they don’t do the same thing, they all do something very shallow, they save you from repeated dotted [attribute] lookups, they don’t do setup and tear down. Just because it’s the same name don’t think it’s the same thing. The with statement is a very big deal.1

Raymond Hettinger, Eloquent Python evangelist

In this chapter, we will discuss control flow features that are not so common in other languages, and for this reason tend to be overlooked or underused in Python. They are:

  • The with statement and context managers

  • The else clause in for, while, and try statements

The with statement sets up a temporary context and reliably tears it down, under the control of a context manager object. This prevents errors and reduces boilerplate code, making APIs at the same time safer and easier to use. Python programmers are finding lots of uses for with blocks beyond automatic file closing.

The else clause is completely unrelated to with. But this is Part V, and I couldn’t find another place for covering else, and I wouldn’t have a one-page chapter about it, so here it is.

Let’s review the smaller topic to get to the real substance of this chapter.

Do This, Then That: else Blocks Beyond if

This is no secret, but it is an underappreciated ...

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

Fluent Python, 2nd Edition

Fluent Python, 2nd Edition

Luciano Ramalho

Publisher Resources

ISBN: 9781491946237Errata Page