Search code examples
pythonpython-3.xpython-decorators

Python: Decorator which return other decorator


I have 2 classes used as decorators

class A:
    """This is a decorator"""
    pass

class B:
    """This is also a decorator"""
    pass

And a third class which I'd like to return either A or either B

class C:
    def a(func):
        return A

    def b(func):
        return B


@C.a
def some_func(some_arg):
    pass

@C.b
def other_func(some_arg):
    pass

Is it possible such this, and if so how to implement it?

UPDATE: The problem is that when creating decorator 'call' is executed during creating. I want to access some configurations, which are set later. So I basically what I'm trying to do is to return wrapper, which return wrapper.

class C:
    def __call__(func):
        def wrapper(*args, **kwargs):
             # Do something with global data
             return func(*args, **kwargs)
        return wrapper

Solution

  • If you want your exact code to work, all you need to do is change your methods to attributes:

    class C:
        a = A
        b = B
    

    It is questionable whether this is a good idea, though. If you want to have a decorator that does one of two different things, a second-order-decorator (i.e. a function returning a decorator) might be more appropriate.