Magic methods

Martin McBride, 2018-10-14
Tags duck typing
Categories magic methods
In Python language

Python makes extensive use duck typing. This means that when we deal with objects in our code, we are often less concerned with what type of object it is, we really only need to know if it can do certain things.

Under the hood, Python uses various magic methods to implement duck typing. These methods have special names - the begin and end in double underscores, for example __len__. For this reason they are sometimes called dunder methods (double underscore, geddit?).

The great thing is that we can implement these magic methods in our own classes, to create new types that can interact with the Python interpreter in all sorts of useful ways. It is almost like being able to extend the language itself.

Duck typing

For example:

def print_len(x):

This function accepts an object x and prints that object's length. We know that the built-in function len works with various types of object - strings, lists and tuples for example. We also know that len doesn't work with other types of objects, for example you can't find the len of an integer.

In fact, what len actually does is to check whether x implements the __len__ method (strings, lists, tuples do, integers don't). It then calls the method if it is available, or raises a TypeError if not.

That is great news, because it means that if we create a class that implements __len__, it will work the len function automatically, and that means it will also work with our print_len function.

Magic methods

There are quite few magic methods and they allow you to control a lot of aspects of how your classes behave. You can:

  • Control how your class is displayed by the print function
  • Allow it to take part in for loops like a range or list object
  • Make it indexable like a list
  • Make it callable like a function
  • Define how it behaves when used with operators such as +, -, < etc

These are covered in detail in the rest of the articles in this section.

If you found this article useful, you might be interested in the book Functional Programming in Python, or other books, by the same author.