Skip to content Skip to sidebar Skip to footer

How Can I Send Unknown List Of Arguments To A Python Decorator -- When The Decorator Is A Method Of A Different Class?

This question is related to another question I just asked. I have created a python decorator as shown below. I want this decorator to accept an unknown list of arguments. But there

Solution 1:

Here's my approach to coding your decorator:

classA:
    def__init__(self, func=None, **kargs):
        self.args  = func
        self.kargs = kargs 
    def__call__(self, decorated_function): 
        defwrapper_func(*args, **kargs):
            print kargs
            return decorated_function(*args, **kwargs)
        if self.func:
            #..do something..return wrapper_func
        elif'xyz'in self.kargs:
            #...do something else here..return wrapper_func
        else:
            ...


classB:
    @A(arg_1="Yolo", arg2="Bolo")              # A(...)(my_func)defmy_func():
        print"Woo Hoo!"

This is a typical way of coding decorators. Class A returns a callable object when called. The callable object of class A will be called automatically for decoration. When the callable object is called, its __call__ method gets triggered and its __call__ operator overloading method returns the wrapper function after performing some customization. The wrapper function is the function that wraps logic around your original function.

Post a Comment for "How Can I Send Unknown List Of Arguments To A Python Decorator -- When The Decorator Is A Method Of A Different Class?"