Search code examples
pythonmass-assignmentdestructuring

Assign multiple variables at once with dynamic variable names


I'm aware I can assign multiple variables to multiple values at once with:

(foo, bar, baz) = 1, 2, 3

And have foo = 1, bar = 2, and so on.

But how could I make the names of the variables more dynamic? Ie,

somefunction(data,tupleofnames):
    (return that each name mapped to a single datum)

somefunction((1,2,3),(foo,bar,baz))     

And have the same?


Solution

  • How about this?

    def somefunction(data, tupleofnames):
        length = len(tupleofnames)
        for i in range(0, length):
            globals()[tupleofnames[i]] = data[i]
    

    Here I assume both data and tupleofnames are lists where tupleofnames is a list of strings. But as Thomas mentioned this is not a good practice. It can easily corrupt your app.