Search code examples
pythonvariablesexeckeyword-argument

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


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)

Solution

  • 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)