Is it possible to add a parameter to a function with a decorator in Python?

Viewed 42

So I tried to write a decorator function to secure the access to a function with a "password string" auth. The decorator function looks like this:

from functools import wraps

def decorator(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        if "auth" in kwargs.keys():
            if kwargs["auth"] == "12345":
                func(*args, **kwargs)
                return
        print("Not authorized.")

    return wrapper

The definition of the example function I want to secure looks like this:

@decorator
def add(list, elem, auth):
    list.append(elem)

In my main code, I am calling add() like this:

def main():
    lst = [3,5]
    add(lst, 2, auth="12345")
    print(lst)


if __name__ == "__main__":
    main()

My goal is to be able to do this, without explicitly mentioning auth in add()'s definition, so I can just do this:

@decorator
def add(list, elem):
    list.append(elem)

Is this even possible?

1 Answers

You should be able to get what you want with:

if kwargs.pop("auth", None) == "12345":

You need to remove the "auth" argument since you are using it and don't want to pass it to the child.

You should also replace

func(*args, **kwargs)
return

with

return func(*args, **kwargs)

in case you happen to be calling a function that returns a value.

Related