[Python] creating decorator out of another decorator (python)

Discussão em 'Python' iniciado por Stack, Fevereiro 28, 2025.

  1. Stack

    Stack Membro Participativo

    After spending several hours on the topic of decorators in python, I still have two issues.

    First; if you have decorator without argument, sytntax is like this:

    @decorator
    def bye():
    return "bye"


    which is just a syntactic sugar and is same as this

    bye = decorator(bye)


    but if I have a decorator with argument:

    @decorator(*args)
    def bye():
    return "bye"


    How does "no-sugar" version looks like? Is the function passed inside as one of the arguments?

    bye = decorator("argument", bye)


    Second issue(which is related to the first, yet more practical example);

    def permission_required(permission):
    def wrap(function):
    @functools.wraps(function)
    def wrapped_func(*args, **kwargs):
    if not current_user.can(permission):
    abort(403)
    return function(*args, **kwargs)
    return wrapped_function
    return wrap

    def admin_required(f):
    return permission_required(Permission.ADMINISTER)(f)


    Here permission_required decorator is passed to a return statement of newly created decorator named admin_required. I have no idea how this works. Mainly the return statement where we returning original decorator + the function(in strange syntax). Can someone elaborate on this? - details are extremely welcome

    Continue reading...

Compartilhe esta Página