Conditional decoration
Emile van Sebille
emile at fenx.com
Mon Jun 18 18:49:24 EDT 2012
On 6/18/2012 3:16 PM Roy Smith said...
> Is there any way to conditionally apply a decorator to a function?
> For example, in django, I want to be able to control, via a run-time
> config flag, if a view gets decorated with @login_required().
>
> @login_required()
> def my_view(request):
> pass
class myDecorator(object):
def __init__(self, f):
self.f = f
def __call__(self):
print "Entering", self.f.__name__
self.f()
print "Exited", self.f.__name__
def null(a): return a
#if condition:
myDecorator = null
@myDecorator
def aFunction():
print "aFunction running"
aFunction()
Cobbled together from http://www.chrisevans3d.com/pub_blog/?p=530 and
http://stackoverflow.com/questions/3687046/python-sphinx-autodoc-and-decorated-members
HTH
Emile
More information about the Python-list
mailing list