Subclassing built-in types
Subclassing built-in types in Python is pretty straightforward. A built-in type called object
is a common ancestor for all built-in types as well as all user-defined classes that have no explicit parent class specified. Thanks to this, every time a class that behaves almost like one of the built-in types needs to be implemented, the best practice is to subtype it.
Now, we will show you the code for a class called distinctdict
, which uses this technique. It is a subclass of the usual Python dict
type. This new class behaves in most ways like an ordinary Python
dict
. But instead of allowing multiple keys with the same value, when someone tries to add a new entry with an identical value, it raises a ValueError
subclass with a help message:
class DistinctError(ValueError): """Raised when duplicate value is added to a distinctdict.""" class distinctdict(dict): """Dictionary that does not accept duplicate values.""" def __setitem__(self, key, value): ...