Conditional decoration

Gelonida N gelonida at gmail.com
Tue Jun 19 04:33:31 EDT 2012


On 06/19/2012 02:23 AM, Rob Williscroft wrote:
> 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.
>

Your suggestion will unconditionally decorate a function and depending 
on the condition call the original function or not.

However if you want to evaluate the condition only once at decoration 
time, then you had probably to do something like (not tested)
 > def conditional_login_required( f ):
 >    _login_required = login_required()(f)
 >
 >    def decorated( request ):
 >        return _login_required( request )
 >    if condition:
 >         return decorated
 >    else:
 >        return f







More information about the Python-list mailing list