Loading topic
try/except/finally works, and how to use open() to read and write files. The previous chapter showed why cleanup needs a guarantee. This chapter shows how the with statement provides that guarantee and what the as 3 min readtry/except/finally, and basic file handling with open(). You have seen that with closes a file for you. Here you will see the mechanism behind it.3 min readtry/except/finally, how with calls __enter__ and __exit__, and how Python classes and exceptions work. Here you will look closely at the three arguments __exit__ receives and at what its return value does.3 min readtry/except/finally works, and the basics of the with statement and the __enter__/__exit__ protocol. Here you will turn that protocol into working classes, decide what __enter__ should return, and choose between letting an except3 min readyield, basic decorators, try/finally, and the class-based __enter__/__exit__ protocol from the previous chapter.2 min readtry/except/finally, generators, and the basic @contextmanager pattern from the previous chapter. Here you will see what happens when the body of a with block raises, and how to write the generator so cleanup always runs.2 min readwith statement, know how __enter__ and __exit__ work, and can read a class-based or @contextmanager manager. Here you will combine several managers in one with statement and see what order they run in.3 min readwith, __enter__, and __exit__ work, and that you have written a manager with @contextmanager. The contextlib module also ships ready-made managers for common jobs. Using them is shorter and less error-prone than writing your own.2 min readwith works, how __enter__ and __exit__ behave, and how to nest or combine several managers in one with statement. It also assumes you can read basic try/except/finally code.3 min read__enter__ and __exit__, and generator-based managers with @contextmanager. It covers a question those chapters skip: what happens when the same manager object is used more than once, or used inside itself.2 min readwith, __enter__ and __exit__ work, and how @contextmanager generators work. It also assumes you have used async def and await in basic asyncio code.2 min read@contextmanager managers and know how __exit__ receives exception details. It covers the mistakes that cause the most bugs, then shows how to test a manager.2 min read