Is there any way to write decorators within a class structure that nest well? For example, this works fine without classes:
def wrap1(func):
def loc(*args,**kwargs):
print 1
return func(*args,**kwargs)
return loc
def wrap2(func):
def loc(*args,**kwargs):
print 2
return func(*args,**kwargs)
return loc
def wrap3(func):
def loc(*args,**kwargs):
print 3
return func(*args,**kwargs)
return loc
def merger(func):
return wrap1(wrap2(wrap3(func)))
@merger
def merged():
print "merged"
@wrap1
@wrap2
@wrap3
def individually_wrapped():
print "individually wrapped"
merged()
individually_wrapped()
The output is:
1
2
3
merged
1
2
3
individually wrapped
which is what I want. But now let's say that I want to make merged
and individually_wrapped
as static or class methods. This will also work, so long as the decorators are kept out of the class namespace. Is there any good way to put the decorators within the namespace? I'd rather not enumerate all the ways that won't work, but the main problem is that if merger
is a method, it can't access the wrapX
methods. Maybe this is a stupid thing to want to do, but has anyone gotten something like this to work, with all the decorators and decorated methods in the same class?