Home > Blockchain >  How can I turn **kwargs into named variables with values? python
How can I turn **kwargs into named variables with values? python

Time:12-27

The following code did not work, any help would be appreciated.

def testfunc(**kwargs):
    for i in kwargs:
        exec(f"global {i}, {i} = kwargs['{i}']")
    print(a,b,c)

if __name__ == "__main__":
    testfunc(a=1,b=2,c=3)

CodePudding user response:

Use globals() to get the global variable dictionary. Then you can update it directly instead of using exec().

def testfunc(**kwargs):
    globals().update(kwargs)
    print(a,b,c)
  • Related