My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more
Sandeep Panda

27 likes

·

733 reads

6 comments

Sébastien Portebois
Sébastien Portebois
Oct 7, 2019

Dunders, or magic methods, or double-underscore methods, are definitely one of the great things in Python: once you start understanding how Python works, you can really leverage these and make your code much more pythonic.

Adding some dunders to your custom classes transform them to iterables, or other useful types. e.g. If you add __len__ and __getitem__ to your class and you can make use it like an interable. Add an __enter__ and an __exit__ and you can use your custom context in a with ...as ...: block (and get all the benefits, like the guarantee the __exit__ will be called even if an exception is raised.

The «Fluent Python» book really introduced me to these a while ago, and it was the big change. For instance, once you get this, you understand why Python has a len(obj) built in function rather than a obj.len() method: any object which implements a __len__(self): method can be called with len(obj), and this __len__ is also used for other constructs (like the iterable). When I started learning Python, I was always bugged by this len() requiring the object has an argument. Once I understood the dunder paradigm and how it helps the developer implement behaviors using composition, it all made sense and became much more easier to remember (and leverage!)

Recommended reading: Fluent Python (from O’Reilly)

And Raymond Hettinger’s «Beyond PEP8» talk with live code refactoring is a great example on how to leverage dunders to make the code more pythonic, and hide the boilerplate to make the code shorter and focused on the business logic. Really a recommended talk! : youtube.com/watch?v=wf-BqAjZb8M

3
·
Francisco Quintero
Francisco Quintero
Nov 18, 2019

Well, TIL for me as well. I never really imagined they'd had a name 😁

Cool to know.

·
kelwein
kelwein
Dec 11, 2019

Its nice to know these many features. Love this. Thanks Walmartone

·
Shad Mirza
Shad Mirza
Aug 19, 2020

TIL: Dunders

·
·1 reply
Gautam Kumar
Gautam Kumar
May 3, 2022

This post is really amazing walmartone.tech

·
trav
trav
Jul 26, 2022

Wait, is Dunder what the type of method is called? I thought it just meant "double underscore". Like "dunder init dunder." I can't say "dunder" with a straight face lol.

Also would it be camelCase between the dunders, or snake_case? Asking the important questions here.

·