Give function defaults arguments from a dictionary in Python

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

    Sure... hope this helps

    def funcc(x, **kwargs):
        locals().update(kwargs)
        print(x, a, b, c, d)
    
    kwargs = {'a' : 1, 'b' : 2, 'c':1, 'd': 1}
    x = 1
    
    funcc(x, **kwargs)
    
    0 讨论(0)
  • 2021-01-01 18:53

    You can unpack values of dict:

    from collections import OrderedDict
    
    def f(x, a, b):
        print(x, a, b)
    
    d = OrderedDict({'a': 3, 'b':4})
    f(10, *d.values())
    

    UPD.

    Yes, it's possible to implement this mad idea of modifying local scope by creating decorator which will return class with overriden __call__() and store your defaults in class scope, BUT IT'S MASSIVE OVERKILL.

    Your problem is that you're trying to hide problems of your architecture behind those tricks. If you store your default values in dict, then access to them by key. If you want to use keywords - define class.

    P.S. I still don't understand why this question collect so much upvotes.

    0 讨论(0)
提交回复
热议问题