Auto-perform actions when updating a mutable in Python
<p>I know how to use property setters to perform actions every time an attribute of a class is modified to avoid having to code in every action every time the variable is changed.</p>

<p>I wanted to know if it was possible to do the same for mutables, like lists and dictionaries ?</p>

<p>What I want to achieve is the following,</p>

<p>I have a dictionary <code>d = {string : object}</code></p>

<p>with <code>object</code> an instance of a class which has an attribute called <code>x</code>.</p>

<p>when I add a new <code>string:object</code> pair to my dictionary, and that the attribute <code>x</code> of the object is <code>!= 0</code>, then I also add the <code>object</code> to a list called <code>x_instances</code>.</p>

<p>You'd have to use a custom class; you could subclass <code>dict</code> or  <a href="https://docs.python.org/3/library/collections.html#userdict-objects" rel="nofollow"><code>collections.UserDict()</code></a>, and override the appropriate <a href="https://docs.python.org/3/reference/datamodel.html#emulating-container-types" rel="nofollow">container special methods</a> to detect changes.</p>

<p>For example, <code>object[subscription] = value</code> is translated to <code>object.__setitem__(subscription, value)</code>, letting you inspect <code>value</code> and act on that:</p>

<pre><code>class MutationDictionary(dict):
    def __setitem__(self, key, value):
        super().__setitem__(key, value)
        if isinstance(value, SomeClass) and value.x != 0:
            x_instances.append(value)
</code></pre>

<p>Do look over the <a href="https://docs.python.org/3/library/stdtypes.html#dict" rel="nofollow">other methods that <code>dict</code> objects implement</a>; you may want to override <code>dict.setdefault()</code> too for example.</p>

python list dictionary getter-setter