I just started using python a couple of days ago, so I am a complete beginner. Basically what I am trying to do is the following. Imagine that I have a string variable such as:

food = 'bread'

I want to create another variable (integer or another type) so that its name is 'bread', in other words the new variable name should be the value of the string variable "food". How can I do such an assignment? My guess is that it should not take more than two or three lines. I read up and am thinking that I need to use a function called setattr, but am not able to figure out how to use it.

Thank you in advance.

Probably the easiest way to do this is to use the local variable dictionary vars() to create new variables on the fly:

food = 'bread'

vars()[food] = 123

print bread  # --> 123

You can print out vars() to see what's going on.

I tried what you have above; it seems the vars() statement in line 3 requires quotes around 'food':

vars()['food'] = 123

Otherwise works perfect.

I tried what you have above; it seems the vars() statement in line 3 requires quotes around 'food':

vars()['food'] = 123

Otherwise works perfect.

That is fine if you want to do this:

vars()['food'] = 123
print food   # --> 123

The original code wanted to print bread like this:

food = 'bread'
vars()[food] = 123
print bread  # --> 123

There is a difference there!

Now how about in methods to classes where you want to create a variable named 'self.whatever'? It works fine outside of Class methods, but I'm sure there's a way to do this. I've tried

vars()['self.test']

and

vars()[self+'.test']

. Is it possible?

Now how about in methods to classes where you want to create a variable named 'self.whatever'? It works fine outside of Class methods, but I'm sure there's a way to do this. I've tried

vars()['self.test']

and

vars()[self+'.test']

Is it possible?

class sample(object):
    def __init__(self):
        vars(self)['a'] = 10

s = sample()
print s.a
>> 10

Hope this helps.

--Karthik Jayapal

This question has already been answered. Start a new discussion instead.