wRAR
wRAR

Reputation: 25693

Decorator to convert an instance method into a class function

I need to pass several methods as callbacks which don't take the self argument. This is how my current code looks like:

def _do_callback(callback, log, *args):
    try:
        # some common code
        callback(*args)
    except:
        log.error('XX')

class Foo(object):
    def __init__(self):
        self.log = Log('Foo')
        self.cb1_wrapper = lambda x: _do_callback(self.cb1, self.log, x)  # I need a function taking one parameter
        self.cb2_wrapper = lambda x: _do_callback(self.cb2, self.log, x)

    def cb1(self, x):
        # some code accessing self

    def cb2(self, x):
        # some code accessing self

    def register_callbacks(self):
        register('1', self.cb1_wrapper)
        register('2', self.cb2_wrapper)

Is it possible to write some decorator to apply to cb1 and cb2 to be able to pass the result into code that currently takes self.cb1_wrapper?

(I know the title is not ideal, feel free to edit)

Upvotes: 1

Views: 1687

Answers (2)

Sylvain Leroux
Sylvain Leroux

Reputation: 51990

I don't know about a decorator, but you could easily write a "wrapper function" that turns out a bound method to a "callback". Something like that:

def wrap(bound_method):
    return lambda x: _do_callback(bound_method, bound_method.__self__.log, x)

The one (major?) drawback is that you have to use the wrapper at call time:

foo = Foo()
...
my_fnc_using_callback(wrap(foo.cb1))

Upvotes: 0

ecatmur
ecatmur

Reputation: 157324

Sure; just think about how an unwrapped method should look:

def callback(fn):
    def inner(self, *args):
        return _do_callback(fn.__get__(self, type(self)), self.log, *args)
    return inner

class Foo(object):
    def __init__(self):
        self.log = Log('Foo')

    @callback
    def cb1_wrapped(self, x):
        pass

Upvotes: 1

Related Questions