This question already has answers here:
How do I create variable variables?
(17 answers)
Closed last year.
I am looking to create a variable name from two strings in Python, e.g.:
a = "column_number"
b = "_url1"
and then be able to get a variable name "column_number_url1" that I can use.
I appreciate this is in general not a good idea - there are numerous posts which go into why it is a bad idea (e.g. How do I create a variable number of variables? , Creating multiple variables ) - I mainly want to be able to do it because these are all variables which get defined elsewhere in the code, and want a easy way of being able to re-access them (i.e. rather than to create thousands of unique variables, which I agree a dictionary etc. would be better for).
As far as I can tell, the answers in the other posts I have found are all alternative ways of doing this, rather than how to create a variable name from two strings.
>>> a = "column_number"
>>> b = "_url1"
>>> x = 1234
>>> globals()[a + b] = x
>>> column_number_url1
1234
The reason that there aren't many posts explaining how to do this is because (as you might have gathered) it's not a good idea. I guarantee that your use case is no exception.
In case you didn't notice, globals() is essentially a dictionary of global variables. Which implies that you should be using a dictionary for this all along ;)
You can use a dictionary:
a = "column_number"
b = "_url1"
obj = {}
obj[a+b] = None
print obj #{"column_number_url1": None}
Alternatively, you could use eval, but remember to always watch yourself around usage of eval/exec:
a = "column_number"
b = "_url1"
exec(a+b+" = 0")
print column_number_url1 #0
eval is evil
As an alternative to Joel's answer, a dictionary would be much nicer:
a = "column_number"
b = "_url1"
data = {}
data[a+b] = 42
Related
This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 2 years ago.
On my recent project I am facing with new obstruction where I need to declare a variable based on value of another string.
What I need:
'Hai'= 2
The String Hai is initialized at variable x,
x='hai' then I need 'hai'= 2
Now all I want is the value of x to point to a int (different int for different values of x).
So if,
x='bye'
then,
'bye'=20
You need to get a dictionary as #Saadat said:
x = {'hai': 2, 'bye': 20}
Now
x['hai']
Will give 2 and the other key will give 20
Or:
y='hai'
z = x[y] #z=2
Also another worse approach:
if x == 'hai':
hai = 2
elif x == 'bye'
bye = 20
...
As mentioned in the comments, you are describing a dictionary:
A dictionary provides a mapping between two different values (also known as an associative array in other languages). You can declare one in Python like this:
mydict = {"hai": 2, "bye": 20}
print(mydict["hai"])
# 2
print(mydict["bye"])
# 20
You can then use variables as the key to access the dictionary:
mykey = "bye"
print(mydict[mykey])
# 20
For more details, please see the Python docs for dictionaries
If you don't go with dictionary and need to declare a variable name & value at runtime. We can achieve this with setattr()
Try this,
class Sample:
pass
obj = Sample()
x = 'hai'
setattr(obj, x, 20)
print(obj.hai)
This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 4 years ago.
I have some list like:
all0 = [['mortem' 'cliffi' 'gear' 'lerp' 'control']]
all1 = [['video' 'player' 'stori' 'book' 'think' 'narr' 'kill']]
And I want to print it out like
num = 0
print(all+num)
But it didn't work.
How to add a character or a number to a variable name?
Hmm, I am pretty sure that you do not need nor really want it, but Python has provision for computing a variable name. Simply it is a rather advanced feature and the normal way is to use mappings (dict) or sequence (list or tuple) containers.
Here, you would use:
all = []
all.append([['mortem' 'cliffi' 'gear' 'lerp' 'control']])
all.append([['video' 'player' 'stori' 'book' 'think' 'narr' 'kill']])
num = 0
print(all[0])
BTW, this syntax is weird, because you are essentially concatenating adjacent litteral string...
But if you really, really need it you can build a interpolator of variables:
def getvar(name):
if name in locals():
return locals()[name]
elif name in globals():
return globals()[name]
else:
raise NameError(repr(name) + ' is not defined')
You can then do:
all0 = [['mortem' 'cliffi' 'gear' 'lerp' 'control']]
all1 = [['video' 'player' 'stori' 'book' 'think' 'narr' 'kill']]
num = 0
print(getvar("all%d" % num))
and get as expected:
[['mortemcliffigearlerpcontrol']]
You can use eval() for that.
eval('print(all{})'.format(num))
But this is really bad style. Don't do this. You should refactor your code and use for loops to go through your lists e.g.
all = [['mortem' 'cliffi' 'gear' 'lerp' 'control']]
all.append(['video' 'player' 'stori' 'book' 'think' 'narr' 'kill'])
for l in all:
print(l)
Leaving aside how bad an idea it might be (probably really bad), variable names are just keys in a Python dict. A one-line solution might be:
vars()[new_name] = vars().pop(old_name)
for global variables, and
vars(some_obj)[new_name] = vars(some_obj).pop(old_name)
for variables of some_obj object.
def function(x):
x = 4
variable = 0
function(variable)
print(variable)
This would output 0 but is there a way that it outputs 4? And also it should be without return.
First of all, I'd suggest you take a look to this nice explanation about python names and values. Now, one possible way to achieve what you want would be using a mutable structure as a dictionary, so you can pass your variable inside, something similar to this would do it:
def function(dct):
dct['variable'] = 4
dct = {
'variable': 0
}
function(dct)
print(dct['variable'])
More info can be found in python docs
I am trying to do the following in python: I have a list which contains some string values. The list looks like this:
parameters = ['RH', 'WindSp_Avg', 'WindDir']
What I want to do - and I really hope the question is not ridiculous - is to create three lists which each of them have the name of the "parameters" list.
For example:
RH = []
WindSp_Avg = []
WindDir = []
I am new in python and although I had searched a bit online I couldn't find some elegant way to do something like this.
I am trying something like this:
for i in parameters:
parameters[0] = []
But it doesn't seem to work. Any suggestions?
Thanks
Dimitris
What you are trying to do is very unsafe and is against all good practices. Is there a problem in simply creating a dictionary?
myVars = {}
for param in parameters:
myVars[param] = []
WARNING The following code is for educational purposes! DO NOT USE IT IN REAL CODE!
You can do a hard hack to add dynamically a variable to the local variables inside a function. Normally locals() represent all local variables. However simply adding to that dictionary won't solve the problem. There is a hack to force Python to reevaluate locals by using exec, for example:
def test():
for param im parameters:
locals()[param] = []
exec ""
print WindSp_Avg
and result:
>>> test()
[]
parameters = ['RH', 'WindSp_Avg', 'WindDir']
for i in parameters:
vars()[i] = [];
print locals()
To create a variable you can do so:
parameters = ['RH', 'WindSp_Avg', 'WindDir']
for i in parameters:
exec("%s = []" % i);
print vars()
you could something like this:
code = "{0} = []"
for i in parameters:
codeobj = compile(code.format(i), "/dev/null", "single")
eval(codeobj)
but i think tha's very unsafe. Because it could be something in parameters and that will be excuted by the eval. So please only use this if it's only really necessary and security is less important.
I want to use a while loop to initialize class objects with a simple incremented naming convention. The goal is to be able to scale the number of class objects at will and have the program generate the names automatically. (ex. h1...h100...h1000...) Each h1,h2,h3... being its own instance.
Here is my first attempt... have been unable to find a good example.
class Korker(object):
def __init__(self,ident,roo):
self.ident = ident
self.roo = roo
b = 1
hwinit = 'h'
hwstart = 0
while b <= 10:
showit = 'h' + str(b)
print(showit) #showit seems to generate just fine as demonstrated by print
str(showit) == Korker("test",2) #this is the line that fails
b += 1
The errors I get range from a string error to a cannot use function type error.... Any help would be greatly appreciated.
If you want to generate a number of objects, why not simply put them in an array / hash where they can be looked up later on:
objects = {}
for b in range(1,11):
objects['h'+str(b)] = Korker("test", 2)
# then access like this:
objects['h3']
Of course there are ways to make the names available locally, but that's not a very good idea unless you know why you need it (via globals() and locals()).
Variables are names that point to objects that hold data. You are attempting to stick data into the variable names. That's the wrong way around.
instead of h1 to h1000, just call the variable h, and make it a list. Then you get h[0] to h[999].
Slightly different solution to viraptor's: use a list.
h = []
for i in range(10):
h.append(Korker("test",2))
In fact, you can even do it on one line with a list comprehension:
h = [Korker("test", 2) for i in range(10)]
Then you can get at them with h[0], h[1] etc.