Last active
September 6, 2018 22:23
-
-
Save denibertovic/9860941 to your computer and use it in GitHub Desktop.
Python decorator with arguments
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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): | |
... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I would recommend elevating the warps call into the decorator, saves a step and makes it cleaner to user:
Usage: