List of used decorators on a function
|Reported by:||Mitar||Owned by:||nobody|
|Has patch:||no||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
Sometimes it is useful to be able to check which decorators are already applied to a function (view mostly), especially when you are constructing them dynamically. I am proposing that all decorators in Django maintain a list of used decorators on a function. It is required that all decorators do this for the idea to be useful.
def user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME, decorator_id=None): """ Decorator for views that checks that the user passes the given test, redirecting to the log-in page if necessary. The test should be a callable that takes the user object and returns True if the user passes. It maintains `decorators` attribute on wrapped function with list of all ids of used decorators, where the first one is the first one used. """ if not login_url: from django.conf import settings login_url = settings.LOGIN_URL if decorator_id is None: decorator_id = id(user_test_required) def decorator(view_func): def _wrapped_view(request, *args, **kwargs): if test_func(request.user): return view_func(request, *args, **kwargs) path = urlquote(request.get_full_path()) tup = login_url, redirect_field_name, path return HttpResponseRedirect('%s?%s=%s' % tup) wrapped_view_func = wraps(view_func, assigned=available_attrs(view_func))(_wrapped_view) wrapped_view_func.decorators =  if hasattr(view_func, 'decorators'): wrapped_view_func.decorators += view_func.decorators wrapped_view_func.decorators.append(decorator_id) return wrapped_view_func return decorator
decorator_id can in fact be anything. Developer can for example use a tuple with additional information. In this case it could be maybe useful to use
(id(user_test_required), id(test_func)) to differentiate between different uses of decorator. Or in the case of
perm parameter could be stored in the tuple.
Of course this functionally can be also made into a decorator. ;-) So we could have a decorator which we would apply to decorators to have them registered in
I am willing to make a patch if there will be confirmation for this idea.