Python and Friends

Python and Friends

Share this post

Python and Friends
Python and Friends
Understanding Python Context-Managers for Absolute Beginners

Understanding Python Context-Managers for Absolute Beginners

Understand the WITH keyword with lightsabers

Mike Huls's avatar
Mike Huls
May 24, 2024
∙ Paid

Share this post

Python and Friends
Python and Friends
Understanding Python Context-Managers for Absolute Beginners
1
Share

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.

Already a paid subscriber? Sign in
© 2025 Mike Huls
Privacy ∙ Terms ∙ Collection notice
Start writingGet the app
Substack is the home for great culture

Share