Skip to content

Instantly share code, notes, and snippets.

@VictorDarvariu
Created March 6, 2020 16:44
Show Gist options
  • Select an option

  • Save VictorDarvariu/243773079e4e954bbda85ab505ebc270 to your computer and use it in GitHub Desktop.

Select an option

Save VictorDarvariu/243773079e4e954bbda85ab505ebc270 to your computer and use it in GitHub Desktop.
Simple example of a custom decorator with arguments in Python.
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