bholben
bholben

Reputation: 1087

Using a string as a variable name

I'm collecting a lot of form parameters. Instead of writing repetitive lines like this:

def post(self):
    var1 = self.request.get('var1')
    var2 = self.request.get('var2')
    var3 = self.request.get('var3')
    var4 = self.request.get('var4')
        ...

...Is there a way to put this into a loop? Perhaps something like this:

def post(self):
    var_list = ['var1', 'var2', 'var3', 'var4', ...]
    for var in var_list:
        var = self.request.get(var)

The problem with my loop is that var is a string and I need it to actually be a variable name on the last line. How could I do this?

Upvotes: 0

Views: 199

Answers (3)

sshashank124
sshashank124

Reputation: 32189

Why not use a list instead:

def post(self):
    vars_list = []
    var_list = ['var'+str(i) for i in range(1,10)]
    for var in var_list:
        vars_list.append(self.request.get(var))

Upvotes: 0

0x90
0x90

Reputation: 40972

Define MAX_VAR_NUM and use the following:

MAX_VAR_NUM=1000
var = [self.request.get("var"+str(i)) for i in xrange(1,MAX_VAR_NUM)]

You can add MAX_VAR_NUM as an attribute for the object instance:

var = [self.request.get("var"+str(i)) for i in xrange(1,self.max_var_num)]

Upvotes: 0

Burhan Khalid
Burhan Khalid

Reputation: 174614

What you have written will work, but you are overwriting the value in the assignment, since you repeat var. Instead, collect the results in a list:

def post(self):
    var_list = ['var1', 'var2']
    result_list = []
    for var in var_list:
        result_list.append(self.request.get(var))
    return result_list # etc.

You can further simplify it by using a list comprehension:

def post(self):
    return [self.request.get(var) for var in ['var1', 'var2']]

Upvotes: 1

Related Questions