References
Before writing this question, I have referred some of the following interesting questions and feel that this scenario is not explained/covered:
- How to make a chain of function decorators? (especially answer #2)
- How to decorate a method inside a class?
- Python decorators in classes
- Python Class Based Decorator with parameters that can decorate a method or a function (close but not exactly what I am asking)
I have a function
as follows:
def simple_function():
print 'this is a simple_function'
And, I have the following class
with some methods
class Test:
def Test_method_1(self, func, args=None, kwargs=None):
print 'this is Test::Test_method_1'
<execute some instructions here>
def Test_method_2(self):
print 'this is Test::Test_method_2'
I am using Test_method_1
and simple_function
as follows:
t = Test()
t.Test_method_1(simple_function)
Say if the simple_function
takes arbitrary arguments, then the Test_method_1
is called as follows:
def simple_function(a, b, c, d=f, g=h):
print 'this is a simple_function'
t = Test()
t.Test_method_1(simple_function, args=[a, b, c], kwargs={d:f, g:h})
Now, I want to use Test_method_2
as a decorator version
of Test_method_1
. So the simple_function
definition can be written as follows:
t = Test()
@t.Test_method_2
def simple_function():
print 'this is a simple_function'
Note: the Test_method_2
will call Test_method_1
with appropriate arguments.
Now the questions:
- 1 - Is this possible?
- 2 - If possible, how do the name of the decorated function (here
simple_function
) will be passed as a argument toTest_method_2
(including theself
)? - 3 - [Here is the killer question, I believe] I want to pass arbitrary arguments to both
Test_method_2
(the decorator) andsimple_function
(the function being decorated) -*args and **kwargs
- How should theTest_method_2
be defined to receive arguments (including theself
)?
The usage of Test_method_2
as a decorator for simple_function
with arbitrary arguments for both is as follows:
t = Test()
@t.Test_method_2(a, b, c, d, e=f, g=h)
def simple_function(x, y, z, n=m):
print 'this is a simple_function'