I declare a variable, say:
var=33
I want to assign to another variable the string ‘var’, that is , how to get the symbol’s name of the value of the variable.
How can I do it ?
I reformulate the question.
WHITE=0
RED=1
BLACK=2
X=2.
I want to assign the value ‘BLACK’ to a variable, say, Y, taking into account that X=2.
It is hard to formulate exactly this question.
I want to avoid a code like this:
color=''
if X==0:
color='WHITE'
elif X==1:
etc.
Is it possible to get the name of the color-variable as a string?
No, you don’t want to do that. Use a dict:
Technically, you could use the
dictfromglobals()orlocals()to store this, and it would be available as a “real variable”, but really, there’s no good reason to do that, it will make your code much more difficult to understand.The way to avoid the code you give:
Is with:
This eliminates sequential ifs, and maintenance beyond expanding
COLORS. You could also do:But that requires manual management of the indices (keys) also.