Conditional decoration

Rob Williscroft rtw at rtw.me.uk
Mon Jun 18 20:23:55 EDT 2012


Roy Smith wrote in news:jro9cj$b44$1 at panix2.panix.com in 
gmane.comp.python.general:

> 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

You need to create a decorator that calls either the original
function or the decorated funtion, depending on your condition, 
Something like (untested):

def conditional_login_required( f ):
  _login_required = login_required()(f)
  
  def decorated( request ):
    if condition == "use-login":
      return _login_required( request )
    else:
      return f( request )
  
  return decorated

@conditional_login_required
def my_view(request):
  pass

Replace (condition == "use-login") with whatever your "run-time 
control flag" is.

-- 
Rob.
    





More information about the Python-list mailing list