Created
March 6, 2020 16:44
-
-
Save VictorDarvariu/243773079e4e954bbda85ab505ebc270 to your computer and use it in GitHub Desktop.
Simple example of a custom decorator with arguments in Python.
This file contains hidden or 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 collections import namedtuple | |
| User = namedtuple('User', field_names=['username', 'role']) | |
| current_user = User(username='Jeff', role='red') | |
| def role_required(required_role): | |
| def has_role(current_user): | |
| return current_user.role == required_role | |
| def role_decorator(func): | |
| def function_wrapper(*args, **kwargs): | |
| if has_role(current_user): | |
| func(*args, **kwargs) | |
| else: | |
| raise Exception(f'not allowed :(. requires role <<{required_role}>>') | |
| return function_wrapper | |
| return role_decorator | |
| @role_required('red') | |
| def red_zone(): | |
| print('Entered red zone successfully') | |
| @role_required('blue') | |
| def blue_zone(): | |
| print('Entered blue zone successfully') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment