'How to pass all the keywords argument to decorator

def provide(**provided_kwargs):
    def decorator(fun):
        def decorated(*args, **kwargs):
            return fun(*args, **kwargs)

        return decorated
    return decorator

The decorator should provide the decorated function with all keyword argument passed to decorators



Solution 1:[1]

You don't have to pass the provided keyword arguments to decorator as they are already available in the decorated function. There you can use them to update the original kwargs:

def provide(**provided_kwargs):
    print(f"Inside provide. Provided kwargs: {provided_kwargs}")

    def decorator(fun):
        print(f"Inside decorator. Provided kwargs: {provided_kwargs}")

        def decorated(*args, **kwargs):
            print(f"Inside decorated. Original args: {args}")
            print(f"Inside decorated. Original kwargs: {kwargs}")
            print(f"Inside decorated. Provided kwargs: {provided_kwargs}")

            # Update original kwargs with the provided kwargs
            both = {**kwargs, **provided_kwargs}
            print(f"Merged kwargs: {both}")

            return fun(*args, **both)

        return decorated

    return decorator


@provide(b=33)
def test(*args, **kwargs):
    print(f"Inside test function. Args: {args}")
    print(f"Inside test function. Kwargs: {kwargs}")


a = 1
test(a, b=3, c=5)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dan Constantinescu