Re-use a global function within a class decorator
<p>Suppose I have a function that generates a router function which invokes specified callbacks depending on whether a number is odd or even:</p>

<pre><code>def odd_even_router(odd, even):
    def r(n):
        if n % 2:
            odd(n)
        else:
            even(n)
    return r
</code></pre>

<p>I also have a class decorator that attaches a similar router method, named <code>check_number</code>, to a class:</p>

<pre><code>def attach_default_router(cls):
    def route(self, n):
        if n % 2:
            self.on_odd(n)
        else:
            self.on_even(n)

    cls.check_number = route
    return cls
</code></pre>

<p>Then, a class decorated with <code>@attach_default_router</code> has <code>check_number()</code> defined automatically, and only has to implement <code>on_odd()</code> and <code>on_even()</code>:</p>

<pre><code>@attach_default_router
class A(object):
    def on_odd(self, n):
        print 'Odd number'

    def on_even(self, n):
        print 'Even number'
</code></pre>

<p>If I want to re-use <code>odd_even_router()</code>, the router function generator, inside <code>attach_default_router()</code>, I may do this:</p>

<pre><code>def attach_default_router(cls):
    def route(self, n):
        r = odd_even_router(self.on_odd, self.on_even)
        r(n)

    cls.check_number = route
    return cls
</code></pre>

<p>However, an undesirable effect is that, every time <code>check_number()</code> gets called, a new (but identical) router function is generated. So here is my question: <strong>How could I re-use <code>odd_even_router()</code> generator inside <code>attach_default_router()</code> decorator, but without generating a new router function every time?</strong></p>

<p>The issue at heart is: <code>odd_even_router()</code> returns a function that takes one argument, but <code>check_number()</code>, being an instance method, needs two (the first being the object's <code>self</code>). If I don't get hold of <code>self</code>, I cannot generate the router function yet. When I get hold of <code>self</code>, I am already inside the method, and generating it there entails generating every time the method is called.</p>

<p>How could I resolve this dilemma?</p>