decorator to set attributes of function

前端 未结 3 1429
无人共我
无人共我 2020-12-09 19:58

I want different functions to be executable only if the logged in user has the required permission level.

To make my life more complexly simply I want to use decorat

3条回答
  •  青春惊慌失措
    2020-12-09 20:24

    The problem is that, even though you are setting the desired property to the wrapped function in inner, inner is returning whatever is returned by the decorated function, which usually never is the function itself.

    You should just return the very same original function with the attribute added, thus you do not really want to worry about what arguments this original decorated function might take, meaning you can get rid of one of the wrapping levels:

    def permission(permission_required):
       def wrapper(func):
           setattr(func, 'permission_required', permission_required)
           return func
       return wrapper
    
    @permission('user')
    def do_x(arg1, arg2):
        pass
    
    @permission('admin')
    def do_y(arg1, arg2):
        pass
    

    This works just fine:

    >>> do_x
    
    >>> do_x.permission_required
    'user'
    >>> do_y.permission_required
    'admin'
    

提交回复
热议问题