TIL: "Double Underscores" have a name - Dunder 😂
Subscribe to my newsletter and never miss my upcoming articles
How many times have you encountered names like
__doTask___ and so on? These are called Dunders or Double Underscores and are commonly used for operator overloading.
More details here: geeksforgeeks.org/dunder-magic-methods-python
Although I have been coding actively for last 6 years, I never knew there is something called Dunder. 😂
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
__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