Menu

1 / 2

Context Managers Beyond Opening Files in Python - MachineLearningMastery.com

Reading 0:00
15s threshold

In this article, you will learn how Python context managers work beneath the surface, and how to apply them to real cleanup problems well beyond file handling.

Topics we will cover include:

How the with statement’s protocol works, including what __enter__() and __exit__() actually do and why the return value of __exit__() matters.

How to build custom context managers using a class, the @contextmanager decorator, and standard library tools like TemporaryDirectory and patch.dict() .

How to manage a runtime-variable number of resources safely using ExitStack , and when to wrap it in a class of its own.

The evaluation script does a fair amount of housekeeping before it evaluates anything. There is a scratch directory for the extracted test set, an environment variable that points the model cache at a faster disk, a library logger turned down to WARNING because it otherwise floods the console, and a stopwatch.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.