DEV Community

Discussion on: How to write better Python classes using Magic Methods

Collapse
 
waylonwalker profile image
Waylon Walker • Edited

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.

class Runner: 
    def __init__(self, who): 
        print(f'Getting ready to go for a run with {who}')
        self.who = who

    def __enter__(self): 
        print(f"Putting {self.who}'s shoes on.") 
        return self.who

    def __exit__(self, exc_type, exc_value, exc_traceback): 
        print(f"Taking {self.who}'s shoes off") 


with Runner(who = 'Waylon') as r:
    print(f'running with {r}')
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
Collapse
 
bikramjeetsingh profile image
Bikramjeet Singh

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.

Collapse
 
waylonwalker profile image
Waylon Walker

For sure, it definitely deserves an article of its own. Just adding to the discussion.