title: Intercept operator lookup on metaclass
body: <p>I have a class that need to make some magic with every operator, like <code>__add__</code>, <code>__sub__</code> and so on.</p>
  
  <p>Instead of creating each function in the class, I have a metaclass which defines every operator in the operator module.</p>
  
  <pre><code>import operator
  class MetaFuncBuilder(type):
      def __init__(self, *args, **kw):
          super().__init__(*args, **kw)
          attr = '__{0}{1}__'
          for op in (x for x in dir(operator) if not x.startswith('__')):
              oper = getattr(operator, op)
  
              # ... I have my magic replacement functions here
              # `func` for `__operators__` and `__ioperators__`
              # and `rfunc` for `__roperators__`
  
              setattr(self, attr.format('', op), func)
              setattr(self, attr.format('r', op), rfunc)
  </code></pre>
  
  <p>The approach works fine, but I think It would be better if I generate the replacement operator only when needed.</p>
  
  <p>Lookup of operators should be on the metaclass because <code>x + 1</code> is done as <code>type(x).__add__(x,1)</code> instead of <code>x.__add__(x,1)</code>, but it doesn't get caught by <code>__getattr__</code> nor <code>__getattribute__</code> methods.</p>
  
  <p>That doesn't work:</p>
  
  <pre><code>class Meta(type):
       def __getattr__(self, name):
            if name in ['__add__', '__sub__', '__mul__', ...]:
                 func = lambda:... #generate magic function
                 return func
  </code></pre>
  
  <p>Also, the resulting "function" must be a method bound to the instance used.</p>
  
  <p>Any ideas on how can I intercept this lookup? I don't know if it's clear what I want to do.</p>
  
  <hr>
  
  <p>For those questioning why do I need to this kind of thing, check the full code <a href="http://pastebin.com/rHYLuwYd">here</a>.
  That's a tool to generate functions (<strong><em>just for fun</em></strong>) that could work as replacement for <code>lambda</code>s. </p>
  
  <p>Example:</p>
  
  <pre><code>&gt;&gt;&gt; f = FuncBuilder()
  &gt;&gt;&gt; g = f ** 2
  &gt;&gt;&gt; g(10)
  100
  &gt;&gt;&gt; g
  &lt;var [('pow', 2)]&gt;
  </code></pre>
  
  <p>Just for the record, I don't want to know another way to do the same thing (I won't declare every single operator on the class... that will be boring and the approach I have works pretty fine :). <em>I want to know how to intercept attribute lookup from an operator</em>.</p>