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?
MVG,
assainator
rdb
April 30, 2009, 11:21am
2
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:
self.aaa = 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)
rdb
April 30, 2009, 1:23pm
4
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
rdb
May 1, 2009, 8:22am
6
Well, your code isn’t entirely equivalent. The php equivalent to your code would be:
exec("$".$list[0]."=5;");
Also your code is still less safe than the PHP equivalent, while mine is as unsafe as.
mmm, is there a way to point to a variable?
since this is not the most usefull way (as prosoft pointed out)
assainator
rdb
May 1, 2009, 8:49am
8
Well, what about the method in my first post?
okay, i’ll try that, i just wanted to see what all options where.
MVG,
assainator
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.