title: Catching changes to a mutable attribute in python
body: <p>I am using properties to execute some code every time there is a change to an attribute, like this:</p>
  
  <pre><code>class SomeClass(object):
      def __init__(self,attr):
          self._attr = attr
  
      @property
      def attr(self):
          return self._attr
  
      @attr.setter
      def attr(self,value):
          if self._attr != value:
              self._on_change()
          self._attr = value
  
      def _on_change(self):
          print "Do some code here every time attr changes"
  </code></pre>
  
  <p>And this works great:</p>
  
  <pre><code>&gt;&gt;&gt; a = SomeClass(5)
  &gt;&gt;&gt; a.attr = 10
  Do some code here every time attr changes
  </code></pre>
  
  <p>But if I store a mutable object in <code>attr</code> instead, <code>attr</code> can be modified directly, bypassing the setter and my change-detection code:</p>
  
  <pre><code>class Container(object):
      def __init__(self,data):
          self.data = data
  
  &gt;&gt;&gt; b = SomeClass(Container(5))
  &gt;&gt;&gt; b.attr.data = 10
  &gt;&gt;&gt;
  </code></pre>
  
  <p>Let's assume that <code>attr</code> is only ever going to be used to store an object of type <code>Container</code>. Is there an elegant way to modify <code>SomeClass</code> and/or <code>Container</code> to make <code>SomeClass</code> execute <code>_on_change</code> whenever the <code>Container</code> object stored in <code>attr</code> is modified? In other words, I want my output to be:</p>
  
  <pre><code>&gt;&gt;&gt; b = SomeClass(Container(5))
  &gt;&gt;&gt; b.attr.data = 10
  Do some code here every time attr changes
  </code></pre>