Extending built-ins
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 of this chapter, we looked at how we can 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. In The collections.abc module section of this chapter, we looked at creating an extension to theMapping
abstract base class.
There are other built-in types, but these two groupings are generally applicable to a variety of problems. For example, we could create a dictionary that rejects duplicate values.
The built-in dictionary always updates the value associated...