Loading topic
try/finally provides a real guarantee, and where that tool becomes a5 min readtry/except/finally, define classes with methods, and read and write files with open(). You don't need to write your own context manager yet. That comes in later chapters. Here you will learn exactly what a with statement does, what the as name holds, and wh6 min readtry/except/finally behaves. It also assumes you have used with open(...). Generators and decorators are not needed here.6 min readtry/except/finally, the exception class hierarchy, and the basic shape of a class-based context manager (__enter__ returning a value and __exit__ running on the way out). Here we focus on the three arguments __exit__ receives and on what its return value doe5 min readtry/except/finally, and the basic with open(...) pattern. You should also know that with calls __enter__ and __exit__. Here you will use those two methods to build managers of your own. Generator-based managers come in the next chap5 min read__enter__ and __exit__ as a class works, but it is a lot of ceremony for a short piece of setup and cleanup. The contextlib.contextmanager decorator lets you write the same thing as a single generator function. This chapter covers how that works, what it does with exceptions, and where6 min read@contextmanager function, as covered in the previous chapter. It also assumes you know try/except/else/finally and how generators resume after yield. Here you will learn what happens to an exception raised in a with body when the manager is a 5 min readwith block, know what __enter__ and __exit__ do, and understand how __exit__ can suppress an exception. It covers how to combine several managers in one statement, in what order they run, and what happens when one of them fails.6 min readcontextlib module in the standard library holds ready-made context managers for jobs that come up again and again. Using them keeps your own code short and removes the need to write a new class each time.5 min readwith statement, know the __enter__ and __exit__ protocol, and understand how exceptions travel through __exit__. It also assumes you know that with blocks unwind in reverse order. Everything else is introduced as it appears.5 min read__enter__ and __exit__, and generator-based managers with @contextmanager. It covers a question both styles raise: what happens when the same manager object is used in a second with statement, or in a with statement nested inside6 min readwith statement, the __enter__/__exit__ protocol, and @contextmanager. It also assumes basic asyncio: async def, await, and asyncio.run. The examples use Python 3.11 or newer.5 min readwith calls __enter__ and __exit__, how __exit__ receives exception information, and how @contextmanager turns a generator into a manager. You should also be comfortable with pytest basics. This chapter collects the mistakes that come up most often and shows how to wri5 min read