Give function defaults arguments from a dictionary in Python

后端 未结 8 2268
予麋鹿
予麋鹿 2021-01-01 18:26

Let\'s imagine I have a dict :

d = {\'a\': 3, \'b\':4}

I want to create a function f that does the exact same thing than this function :

8条回答
  •  伪装坚强ぢ
    2021-01-01 18:47

    You cannot achieve this at function definition because Python determines the scope of a function statically. Although, it is possible to write a decorator to add in default keyword arguments.

    from functools import wraps
    
    def kwargs_decorator(dict_kwargs):
        def wrapper(f):
            @wraps(f)
            def inner_wrapper(*args, **kwargs):
                new_kwargs = {**dict_kwargs, **kwargs}
                return f(*args, **new_kwargs)
            return inner_wrapper
        return wrapper
    

    Usage

    @kwargs_decorator({'bar': 1})
    def foo(**kwargs):
        print(kwargs['bar'])
    
    foo() # prints 1
    

    Or alternatively if you know the variable names but not their default values...

    @kwargs_decorator({'bar': 1})
    def foo(bar):
        print(bar)
    
    foo() # prints 1
    

    Caveat

    The above can be used, by example, to dynamically generate multiple functions with different default arguments. Although, if the parameters you want to pass are the same for every function, it would be simpler and more idiomatic to simply pass in a dict of parameters.

提交回复
热议问题