0

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?

3 Answers 3

1

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']]
Sign up to request clarification or add additional context in comments.

2 Comments

Or, they could put it in a dict.
@SethMMorton request.get seems to be a dict-like object already, so not sure what would be the point of that.
0

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)]

Comments

0

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))

1 Comment

You're overwriting the builtin vars()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.