Reputation: 315
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
Upvotes: 0
Views: 53
Reputation: 5185
You can make this work by changing class C to work like this.
class C:
def a(func):
return A(func)
It really boils down to understanding that a decorator is just a syntactic shortcut.
@dec
def f():
pass
is exactly the same as:
def f():
pass
f = dec(f)
Upvotes: 0
Reputation: 27283
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.
Upvotes: 2