hfffoman
hfffoman

Reputation: 25

assignment to multiple indirectly addressed variables

Single assignment works like this: (there may be better ways)

b='bb'
vars()[b] = 10
bb
>>>10

but if I do this:

c='cc'
vars() [b,c]= 10,11

it doesn't successfully assign bb and cc.

I don't understand why, nor how best to do this.

Thanks

PS, several people have asked, quite reasonably, why I wanted to do this. I found I was setting up a lot of variables and objects according to options specified by the user. So if the user specified options 2, 3 and 7, I would want to create a2, a3 and 7, plus b2, b3, b7 etc. It may not be usual practice but using vars and eval is a very easy and transparent way to do it, requiring simple concise code:

For i in input_vector: vars()['a'+input_vector[i]] = create_a (input_vector[i])

For i in input_vector: vars()['b'+input_vector[i]] = create_b (input_vector[i])

This works for some of the data. The trouble is when I use another function, create_c_and_d. This requires me to compress the above two lines into one function call. If this can be done easily using dictionaries, I am happy to switch to that method. I am new to python so it isn't obvious to me whether it can.

Upvotes: 0

Views: 621

Answers (2)

roippi
roippi

Reputation: 25974

I don't understand why, nor how best to do this.

Well, I have to say, uh.. the best way would be to not do it. At all.

Just use a dict like it's supposed to be used:

d = {}
d['aa'] = 10
d['bb'] = 11

Anyway, to answer your question, you're doing the tuple unpacking in the wrong place. Or, rather, not unpacking at all; when you specify a,b to a dict, that means you're assigning a tuple as the key. Instead, unpack like this:

vars()[b], vars()[c] = 10,11

I'll again recommend that you not do this and just use dicts to map strings (or whatever hashable datatype) to values. Dynamically naming variables is not good practice.

Upvotes: 0

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251106

Because b,c is a tuple, so you're actually assiging to the key ('bb', 'cc').

>>> vars() [b,c]= 10,11
>>> vars()[('bb', 'cc')]
(10, 11)

>>> x = b,c
>>> type(x)
<type 'tuple'>

Upvotes: 3

Related Questions