pythonmagic-methods

Why does Python use 'magic methods'?


I'm a bit surprised by Python's extensive use of 'magic methods'.

For example, in order for a class to declare that instances have a "length", it implements a __len__ method, which it is called when you write len(obj). Why not just define a len method which is called directly as a member of the object, e.g. obj.len()?


See also: Why does Python code use len() function instead of a length method?


Solution

  • 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:

    and so on...