Skip to content

Instantly share code, notes, and snippets.

@denibertovic
Last active September 6, 2018 22:23
Show Gist options
  • Save denibertovic/9860941 to your computer and use it in GitHub Desktop.
Save denibertovic/9860941 to your computer and use it in GitHub Desktop.
Python decorator with arguments
from functools import wraps
## helper decorator for making new decorators with arguments
decorator_with_args = lambda decorator: lambda *args, **kwargs: lambda func: decorator(func, *args, **kwargs)
@decorator_with_args
def my_decorator(f, some_argument=None):
@wraps(f)
def wrapper(self, request, *args, **kwargs):
# do something here
pass
return wrapper
# now use it on a django view for example
@login_required
@my_decorator(some_argument='something')
def my_view(request):
...
# Or in a class based view
from django.utils.decorators import method_decorator
class MyEndpoint(Endpoint):
@method_decorator(my_decorator(some_argument='something'))
def get(self, request):
...
@cstobey
Copy link

cstobey commented May 18, 2015

I would recommend elevating the warps call into the decorator, saves a step and makes it cleaner to user:

decorator_with_args = lambda d: lambda *args, **kwargs: lambda func: wraps(func)(d(func, *args, **kwargs))

Usage:

@decorator_with_args
def my_decorator(f, some_argument=None):
    def wrapper(self, request, *args, **kwargs):
            # do something here
            pass
    return wrapper

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment