1
\$\begingroup\$

I use 3 lists to store field name, its value and score. If field name is already added to according list, then I just need to update other 2 lists. If it is not there, then I need to add it. I do the following:

user = User.get_by_key_name(user_key_name)
if user:
    field_names = user.field_names
    field_values = user.field_values
    field_scores = user.field_scores
    if field_name in user.field_names:
        # field_names[field_index] = field_name
        field_index = user.field_names.index(field_name)
        field_values[field_index] = field_value
        field_scores[field_index] = field_score
    else:
        field_names.append(field_name)
        field_values.append(field_value)
        field_scores.append(field_score)
    user.field_names = field_names
    user.field_values = field_values 
    user.field_scores = field_scores
    user.put()

Is it correct approach?

\$\endgroup\$
3
\$\begingroup\$
user = User.get_by_key_name(user_key_name)
if user:

Python convention is to use user is None when checking against None

    field_names = user.field_names
    field_values = user.field_values
    field_scores = user.field_scores

Why copy these references? It doesn't help you much.

    if field_name in user.field_names:
        # field_names[field_index] = field_name
        field_index = user.field_names.index(field_name)

Use index to check if field_name is present. That way it doesn't have to search through the lists twice.

        field_values[field_index] = field_value
        field_scores[field_index] = field_score

If possible, avoid maintaing parrallel lists. In this case, it looks like maybe you should have a dictionary of strings to tuples.

    else:
        field_names.append(field_name)
        field_values.append(field_value)
        field_scores.append(field_score)
    user.field_names = field_names
    user.field_values = field_values 
    user.field_scores = field_scores

Unless user does something odd, this has no effect. Assignment doesn't copy in python, it just copies the references.

    user.put()
\$\endgroup\$
  • \$\begingroup\$ I wanted to mention that in tags, but there is no GAE tag. So, this code is used with GAE. If I use field_index to identify if value is there and it is not, then I get ValueError. Not sure how to save tuples in GAE datastore - stackoverflow.com/questions/9442860/… \$\endgroup\$ – LA_ Feb 27 '12 at 18:41
  • \$\begingroup\$ @LA_, you should catch the ValueError and handle it. I don't know GAE, and you may not able to store tuples. \$\endgroup\$ – Winston Ewert Feb 27 '12 at 21:49

Not the answer you're looking for? Browse other questions tagged or ask your own question.