Glossary

Dunder Method

Also known as: magic method, special method

Dunder methods (short for "double underscore" methods, also called magic methods or special methods) are methods with names like __init__, __str__, __repr__, __len__, __getitem__, __eq__, and __add__. Python calls these methods automatically in response to built-in operations: len(obj) calls obj.__len__(), obj[key] calls obj.__getitem__(key), str(obj) calls obj.__str__(), and a + b calls a.__add__(b).

Dunder methods are the mechanism by which user-defined classes integrate with Python's built-in syntax and functions. By implementing the right dunder methods, your objects can be iterable (__iter__, __next__), comparable (__eq__, __lt__), hashable (__hash__), callable (__call__), context-manageable (__enter__, __exit__), or printable (__str__, __repr__).

The full set of dunder methods is documented in the Python Data Model chapter of the language reference. There are over 100 of them, but most classes only need a handful. The most commonly implemented are __init__ (initialiser), __repr__ (developer representation), __str__ (user representation), __eq__ (equality), and __len__ (length). The dataclasses module auto-generates several of these, and functools.total_ordering fills in comparison methods from just __eq__ and __lt__.

Related terms: Class, Method, Property

Discussed in:

This site is currently in Beta. Please email Chris Paton (cpaton@gmail.com) with any suggestions, questions or comments.