Python Context Managers

python_tutorials

Introduction

One of the most “obscure” features of Python that almost all Python programmers use, even the beginner ones, but don’t really understand, is context managers. You’ve probably seen them in the form of with statements, usually first encountered when you learn opening files in Python. Although context managers seem a little strange at first, when we really dive into them, understand the motivation and techniques behind it, we get access to a new weapon in our programming arsenal. So without further ado, let’s dive into it!

Motivation: Resource Management

As someone much wiser than me said, “Necessity is the mother of invention”. To really understand what a context manager is and how can we use it, we must first investigate the motivations behind it — the necessities that gave rise to this “invention”.

The primary motivation behind context managers is resource management. When a program wants to get access to a resource on the computer, it asks the OS for it, and the OS, in turn, provides it with a handle for that resource. Some common examples of such resources are files and network ports. What’s important to understand is that these resources have limited availability,

To finish reading, please visit source site