I need a python list object which, upon insert, automatically checks for certain constraints of the form: “A must always come before B” or “If C is included, it must always come last”.
What’s the easiest/fastest way to go about implementing this. The obvious approach is to override all the methods of the list data type which alter its contents (append, extend, insert, etc), and verify that constraints still hold after the operation. It’s just that this is pretty tedious as there are a lot of these methods. Is there an easier way?
I would strongly recommend subclassing from the
collections.MutableSequenceabstract base class. The drawback is that it won’t be recognized as a subclass oflist(as user4815162342 points out). However, that should almost never matter as long as people using the resulting class are doing the right thing (i.e. using duck typing or passing abstract base classes rather than concrete classes toisinstance).The wonderful thing about this is that once you’ve defined the following methods, you get the rest of the
MutableSequenceinterface for free. Here’s a concrete subclass ofMutableSequencethat you can use as a template for further customization. In your case, you should only have to customize__init__,__setitem__,insert, and__delitem__. Everything else is defined in terms of those, and so will perform whatever checks you insert:A couple of simple tests: