Understanding Python Context-Managers for Absolute Beginners
Understand the WITH keyword with lightsabers
You are definitely familiar with context managers—they use the with
statement:
with open('somefile.text', 'r') as file:
data = file.read()
In this article we’ll focus on what happens when we call a context manager:
What is a context manager?
How does it work?
What are its advantages?
Creating your own context manager
Let’s code!
Before we take on some real-life example of code using the context manager we’ll understand the inner workings with a clear example: imagining we’re coding a lightsaber.
Setup: coding the lightsaber
I’m pretty sure everyone is familiar with those: the super-dangerous, red-hot plasma blade that slices through everything it touches. Before we use them to stab or slash we need to activate it and after we’re done using it we should always de-activate this insanely dangerous piece of equipment. In code:
Keep reading with a 7-day free trial
Subscribe to Python and Friends to keep reading this post and get 7 days of free access to the full post archives.