python question

let’s say i have a list that contains:(“myvar1”,“myvar2”,“myvar3”)

but i want that those names become a variable themselves.

in php it was not difficult:

$$list[0] = 5;
//that would result into:
$myvar1 = 5;

but how do you do that in python?



Something like:

locals()["aaa"] = 5
#Equivalent to:
aaa = 5

To set it as property of other objects (e.g. a class) use setattr:

setattr(self, aaa, 5)
#Or, like this:
self.__dict__["aaa"] = 5
#Equivalent to: = 5

Still, its not a good practice, and if you are in need of this kind of operations it might be good to reconsider your code design.

how about:

exec "%s=%d"%(list[0], 5)

Because that’s almost the most unsafe code I’ve ever seen. What if the user finds a way to put ‘shutil.rmtree(“c:”)’ in the variable?

but assainator ain’t asked for safe code, he asked for a python equivalent of a php piece of code and now he had it :wink:

Well, your code isn’t entirely equivalent. The php equivalent to your code would be:


Also your code is still less safe than the PHP equivalent, while mine is as unsafe as. :slight_smile:

mmm, is there a way to point to a variable?
since this is not the most usefull way (as prosoft pointed out)


Well, what about the method in my first post?

okay, i’ll try that, i just wanted to see what all options where.



Is there some reason you don’t just store the numbers in a list? As in:
myvars[1] = 5

I guess I’m asking for intent here because just looking at the raw syntax doesn’t tell me much. I don’t see why you need a whole bunch of different variables.