Why does Python use ‘magic methods’?

AFAIK, len is special in this respect and has historical roots.

Here’s a quote from the FAQ:

Why does Python use methods for some
functionality (e.g. list.index()) but
functions for other (e.g. len(list))?

The major reason is history. Functions
were used for those operations that
were generic for a group of types and
which were intended to work even for
objects that didn’t have methods at
all (e.g. tuples). It is also
convenient to have a function that can
readily be applied to an amorphous
collection of objects when you use the
functional features of Python (map(),
apply() et al).

In fact, implementing len(), max(),
min() as a built-in function is
actually less code than implementing
them as methods for each type. One can
quibble about individual cases but
it’s a part of Python, and it’s too
late to make such fundamental changes
now. The functions have to remain to
avoid massive code breakage.

The other “magical methods” (actually called special method in the Python folklore) make lots of sense, and similar functionality exists in other languages. They’re mostly used for code that gets called implicitly when special syntax is used.

For example:

  • overloaded operators (exist in C++ and others)
  • constructor/destructor
  • hooks for accessing attributes
  • tools for metaprogramming

and so on…

Leave a Comment