views:

56

answers:

2

What is the best way to reference datastore model attributes without using the four 'if statements' I have in the below sample code, which seem messy and inefficient. For real-world code I may have a situation of 100 attributes such as self.var1, self.var2, ... self.varN that I want to some how reference with just an integer (or strings) as an argument to some method.

class PixelObject(db.Model):

 zoom0 = db.ListProperty(int)
 zoom1 = db.ListProperty(int)
 zoom2 = db.ListProperty(int)
 zoom3 = db.ListProperty(int)
 zoom4 = db.ListProperty(int)

 def inputZoomData(self, zoomInteger, input_data):
        """input_data goes to specified attribute based on if 0,1,2,3,or 4 is argument"""

  if zoomInteger == 0: self.zoom0 = input_data
  if zoomInteger == 1: self.zoom1 = input_data
  if zoomInteger == 2: self.zoom2 = input_data
  if zoomInteger == 3: self.zoom3 = input_data
  if zoomInteger == 4: self.zoom4 = input_data
+2  A: 

How about using an array of integers, instead of holding five different integer properties?

Extrakun
App Engine Model's cannot have lists stored with a ListProperty attribute so to mimic an array ( or a list of lists) I need to have many attributes where each is a ListProperty.
indiehacker
+2  A: 

I'd also recommend using an array instead of five members to simplify your code:

if 0 <= zoomInteger < len(zooms):
    self.zooms[zoomInteger] = input_data
else:
    # Error handling.

If you can't change the way the class is designed another alternative is to use setattr:

setattr(self, 'zoom' + str(zoomInteger), input_data)
Mark Byers
The 2nd answer is perfect..Thanks! Since I app engine cant have a list of lists in the ListProperty attribute of a datastore model I cant use the 1st answer.
indiehacker
Perhaps if you explain what you're trying to achieve, we can suggest a better way of representing your data.
Nick Johnson