How to automate the delegation of __special_methods__ in Python?
<p>Let <code>spam</code> be an instance of some class <code>Spam</code>, and suppose that <code>spam.ham</code> is an object of some built-in type, say <code>dict</code>.  Even though <code>Spam</code> is not a subclass of <code>dict</code>, I would like its instances to have the same API as a regular <code>dict</code> (i.e. the same methods with the same signatures), but I want to avoid typing out a bazillion boilerplate methods of the form:</p>

<pre><code>    def apimethod(self, this, that):
        return self.ham.apimethod(this, that)
</code></pre>

<p>I tried the following:</p>

<pre><code>class Spam(object):
    def __init__(self):
        self.ham = dict()

    def __getattr__(self, attr):
        return getattr(self.ham, attr)
</code></pre>

<p>...but it works for "regular" methods, like <code>keys</code> and <code>items</code>, but not for <em>special methods</em>, like <code>__setitem__</code>, <code>__getitem__</code>, and <code>__len__</code>:</p>

<pre><code>&gt;&gt;&gt; spam = Spam()
&gt;&gt;&gt; spam.keys()
[]
&gt;&gt;&gt; spam['eggs'] = 42
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
TypeError: 'Spam' object does not support item assignment
&gt;&gt;&gt; spam.ham['eggs'] = 42
&gt;&gt;&gt; foo.items()
[('eggs', 42)]
&gt;&gt;&gt; spam['eggs']
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
TypeError: 'Spam' object is not subscritable
&gt;&gt;&gt; len(spam)
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
TypeError: 'Spam' object has no len()
</code></pre>

<p><br/></p>

<p>All the special methods I tried produced similar errors.</p>

<blockquote>
  <p>How can I automate the definition of <em>special methods</em> (so that they get referred to the delegate)?</p>
</blockquote>

<p>Clarification: I'm not necessarily looking for solutions that leverage the standard method lookup sequence.  My goal here is to minimize boilerplate code.</p>

<p>Thanks!</p>
