Chapter 18. with, match, 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
withstatement, there arewithstatements 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. Thewithstatement is a very big deal.1Raymond Hettinger, eloquent Python evangelist
This chapter is about 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
withstatement and context manager protocol -
Pattern matching with
match/case -
The
elseclause infor,while, andtrystatements
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.
We’ve seen pattern matching in previous chapters,
but here we’ll see how the grammar of a language
can be expressed as sequence patterns.
That observation explains why match/case is an effective tool to create language processors that are easy to understand and extend. We’ll study a complete interpreter for a small but functional ...