👋 Hey there, I am Waylon Walker
I am a Husband, Father of two beautiful children, Senior Python Developer currently working in the Data Engineering platform space. I am a continuous learner, and sha
great article, the dunder methods you outlined here are real classics.
Context Managers
Here are two of my favorites
__enter__
__exit__
Combined together these two create context managers. These are typically used for things like database connections, or opening files. If you do one you should not forget to do the other. Here is an example where we are going for a run, but we only need to put our shoes on for the run. It's a bit abstract, but you can replace the shoes with opening a file or database connection.
classRunner:def__init__(self,who):print(f'Getting ready to go for a run with {who}')self.who=whodef__enter__(self):print(f"Putting {self.who}'s shoes on.")returnself.whodef__exit__(self,exc_type,exc_value,exc_traceback):print(f"Taking {self.who}'s shoes off")withRunner(who='Waylon')asr:print(f'running with {r}')
running this gives us
Getting ready to go for a run with Waylon
Putting Waylon's shoes on.
running with Waylon
Taking Waylon's shoes off
Thanks Waylon, that's a great explanation. I had considered including the methods for context managers, iterators, etc in the article but I guess I thought the topics a bit too complex to be covered in a single bullet point. Nevertheless, I'll add it now with a link to your comment.
👋 Hey there, I am Waylon Walker
I am a Husband, Father of two beautiful children, Senior Python Developer currently working in the Data Engineering platform space. I am a continuous learner, and sha
great article, the dunder methods you outlined here are real classics.
Context Managers
Here are two of my favorites
__enter__
__exit__
Combined together these two create context managers. These are typically used for things like database connections, or opening files. If you do one you should not forget to do the other. Here is an example where we are going for a run, but we only need to put our shoes on for the run. It's a bit abstract, but you can replace the shoes with opening a file or database connection.
running this gives us
Thanks Waylon, that's a great explanation. I had considered including the methods for context managers, iterators, etc in the article but I guess I thought the topics a bit too complex to be covered in a single bullet point. Nevertheless, I'll add it now with a link to your comment.
For sure, it definitely deserves an article of its own. Just adding to the discussion.