I've created a dictionary subclass with a set of default immutable keys.
from collections import MutableMapping
class Bones(MutableMapping):
"""Basic dict subclass for bones, that forbids bones from being deleted
and new bones from being added."""
def __init__(self, init_val=0):
self.bones = {"between_hips": init_val,
"bicep_right": init_val,
"bicep_left": init_val,
"arm_right": init_val,
"arm_left": init_val,
"thigh_right": init_val,
"thigh_left": init_val,
"leg_right": init_val,
"leg_left": init_val,
"spine_lower": init_val,
"spine_upper": init_val}
def __getitem__(self, item):
return self.bones[item]
def __setitem__(self, key, value):
if key in self.bones:
self.bones[key] = value
else:
raise KeyError("Can't add a new bone!")
def __delitem__(self, key):
raise TypeError("Can't delete bones")
def __iter__(self):
return iter(self.bones)
def __len__(self):
return len(self.bones)
Here are a few tests to check that it's working correctly:
from bones import Bones
bn = Bones()
bn["between_hips"] = 1
# these should all raise errors
bn["foo"] = 1
del bn["between_hips"]
Is this the proper way to create the subclass?
Background
My search to do this correctly started at the StackOverflow question "How to 'perfectly' override a dict" where I discovered there were two approaches to doing this. One was sub-classing an Abstract Base Class from the collections
module and the other was actually sub-classing dict
.
The justification for actually sub-classing dict
confused me. Specifically the discussion of the object properties of __dict__
and __slots__
. As best as I can tell from this question, I should be using __slots__
, but I'm super unclear how.