Give function defaults arguments from a dictionary in Python

后端 未结 8 2319
予麋鹿
予麋鹿 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:32

    This question is very interesting, and it seemed different people have their different own guess about what the question really want.

    I have my own too. Here is my code, which can express myself:

    # python3 only
    from collections import defaultdict
    
    # only set once when function definition is executed
    def kwdefault_decorator(default_dict):
        def wrapper(f):
            f.__kwdefaults__ = {}
            f_code = f.__code__
            po_arg_count = f_code.co_argcount
            keys = f_code.co_varnames[po_arg_count : po_arg_count + f_code.co_kwonlyargcount]
            for k in keys:
                f.__kwdefaults__[k] = default_dict[k]
            return f
    
        return wrapper
    
    default_dict = defaultdict(lambda: "default_value")
    default_dict["a"] = "a"
    default_dict["m"] = "m"
    
    @kwdefault_decorator(default_dict)
    def foo(x, *, a, b):
        foo_local = "foo"
        print(x, a, b, foo_local)
    
    @kwdefault_decorator(default_dict)
    def bar(x, *, m, n):
        bar_local = "bar"
        print(x, m, n, bar_local)
    
    foo(1)
    bar(1)
    # only kw_arg permitted
    foo(1, a=100, b=100)
    bar(1, m=100, n=100)
    

    output:

    1 a default_value
    1 m default_value
    1 100 100
    1 100 100
    

提交回复
热议问题