Skip to content
Advertisement

How to obtain parameters from decorated imported function?

i’d like to obtain the parameter from the decorated function. It’s a lil bit different from the usual one.

Here is the code

import functools


def remotable_timer(fn):
    @functools.wraps(fn)
    def wrapper(*args, **kwargs):
        print('remotable_timer', fn, args, **kwargs)
        result = fn(*args, **kwargs)
        return result
    wrapper.original_fn = fn
    return wrapper


def remotable_cache(fn):
    @functools.wraps(fn)
    def wrapper(*args, **kwargs):
        print('remotable_cache', fn, args)
        result = fn(*args, **kwargs)
        return result

    wrapper.original_fn = fn
    return wrapper


remotable = remotable_timer(remotable_cache)


class TestClass(object):
    @remotable
    def test_function(self, context, *args):
        print('test_function', context, *args)


if __name__ == '__main__':
    test = TestClass()
    test.test_function('context', 1, 2, 3)

output: i need fetch: context, 1,2,3(parameters in test_function) in remotable_timer

remotable_timer <function remotable_cache at 0x000002780F7336A8> (<function TestClass.test_function at 0x000002780F733730>,)
remotable_cache <function TestClass.test_function at 0x000002780F733730> (<__main__.TestClass object at 0x000002780F72D898>, 'context', 1, 2, 3)
test_function context 1 2 3

i know the code below can be a potential way to achieve it, but i have to decorate remotable_cache in line anyway. Dose anyone have any idea, i’ll be appreciate it !

class TestClass(object):
    @remotable_timer
    @remotable_cache
    def test_function(self, context, *args):
        print('test_function', context, *args)

Advertisement

Answer

You should change

remotable = remotable_timer(remotable_cache)

to

def remotable(func):
   return remotable_timer(remotable_cache(func))

Here is the result

remotable_timer <function TestClass.test_function at 0x0000010A12B99280> (<__main__.TestClass object at 0x0000010A12B93F70>, 'context', 1, 2, 3)
remotable_cache <function TestClass.test_function at 0x0000010A12B991F0> (<__main__.TestClass object at 0x0000010A12B93F70>, 'context', 1, 2, 3)
test_function context 1 2 3
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement