I have a library proving the following code:
class LibClass:
def decorator_method(self, *args, **kwargs):
# some code...
pass
which is intended to be used as follows:
k = LibClass()
method_args = (,) # something I create
@k.decorator_method(method_args)
def my_func():
# Code that I want to run
Specifically, the library implements some callback-like functionality via these decorators. Naturally, I have no control over the library, nor is there any alternative functionality.
Importantly, the instance of LibClass
is part of the decorator, so my_func
is added to the callbacks of that very instance, k
.
However, I have implemented my_func
elsewhere in my code and I want to separate the function from the decoration. One way would be to create a wrapper like so:
k = LibClass()
@k.decorator_method(method_args)
def my_func_wrapper():
# Actual call
my_func()
This approach works the way I want, but it has the disadvantage of having to define and call the wrapper function which is not strictly necessary. However, I cannot apparently apply the decorator directly, since
def my_func():
# ...
@k.decorator_method(method_args)
my_func
is not valid python code. Similarly, I might think about decorating a closure in this way, like
def my_func_producer(more_args):
def my_func():
# Do something with more_args
return my_func
where
more_args = (,)
@k.decorator_method(method_args)
my_func_producer(more_args)
is also invalid. Is there any way to apply the decorator without having to define an additional wrapper function?