-class choicesList(object): # XXX: we might want a better name for this
- LIST_TYPE_LIST = 1
- LIST_TYPE_DICT = 2
-
- def __init__(self, choices, type = None):
- self.choices = choices
- if type is None:
- if isinstance(choices, list):
- self.type = choicesList.LIST_TYPE_LIST
- elif isinstance(choices, dict):
- self.type = choicesList.LIST_TYPE_DICT
- else:
- assert False, "choices must be dict or list!"
- else:
- self.type = type
-
- def __list__(self):
- if self.type is choicesList.LIST_TYPE_LIST:
- ret = [isinstance(x, tuple) and x[0] or x for x in self.choices]
- else:
- ret = self.choices.keys()
- return ret or [""]
-
- def __iter__(self):
- if self.type is choicesList.LIST_TYPE_LIST:
- ret = [isinstance(x, tuple) and x[0] or x for x in self.choices]
- else:
- ret = self.choices
- return iter(ret or [""])
-
- def __len__(self):
- return len(self.choices) or 1
-
- def __getitem__(self, index):
- if self.type is choicesList.LIST_TYPE_LIST:
- ret = self.choices[index]
- if isinstance(ret, tuple):
- ret = ret[0]
- return ret
- return self.choices.keys()[index]
-
- def index(self, value):
- return self.__list__().index(value)
-
- def __setitem__(self, index, value):
- if self.type is choicesList.LIST_TYPE_LIST:
- if isinstance(self.choices[index], tuple):
- self.choices[index] = (value, self.choices[index][1])
- else:
- self.choices[index] = value
- else:
- key = self.choices.keys()[index]
- orig = self.choices[key]
- del self.choices[key]
- self.choices[value] = orig
-
- def default(self):
- if self.type is choicesList.LIST_TYPE_LIST:
- default = self.choices[0]
- if isinstance(default, tuple):
- default = default[0]
- else:
- default = self.choices.keys()[0]
- return default
-
-class descriptionList(choicesList): # XXX: we might want a better name for this
- def __list__(self):
- if self.type is choicesList.LIST_TYPE_LIST:
- ret = [isinstance(x, tuple) and x[1] or x for x in self.choices]
- else:
- ret = self.choices.values()
- return ret or [""]
-
- def __iter__(self):
- return iter(self.__list__())
-
- def __getitem__(self, index):
- if self.type is choicesList.LIST_TYPE_LIST:
- for x in self.choices:
- if isinstance(x, tuple):
- if x[0] is index:
- return str(x[1])
- elif x is index:
- return str(x)
- return str(index) # Fallback!
- else:
- return str(self.choices.get(index, ""))
-
- def __setitem__(self, index, value):
- if self.type is choicesList.LIST_TYPE_LIST:
- i = self.index(index)
- if isinstance(self.choices[i], tuple):
- self.choices[i] = (self.choices[i][0], value)
- else:
- self.choices[i] = value
- else:
- self.choices[index] = value
-