Extending Built-ins

Learn how we can extend the behaviors of built-in objects in Python.

Mutable and immutable objects

Python has two collections of built-ins that we might want to extend. We can broadly classify these into the following:

  • Immutable objects, including numbers, strings, bytes, and tuples. These will often have extended operators defined. In the operator overloading section, we looked at how to provide arithmetic operations for objects of the Dice class.

  • Mutable collections, including sets, lists, and dictionaries. When we look at the definitions in collections.abc, these are sized, iterable containers, three distinct aspects that we might want to focus on.

There are other built-in types, but these two groupings generally apply to various problems. For example, we could create a dictionary that rejects duplicate values. The built-in dictionary always updates the value associated with a key. This can lead to odd-looking code that works. For example:

Get hands-on with 1200+ tech skills courses.