Handling choices the right way

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class MyChoices:
   def __init__(self, **entries):
       self.__dict__.update(entries)
       self.choices = [ ]
       for val in entries.values():
           for key in entries.keys():
               if entries[key] == val:
                   self.choices.append((val, key))

      def get_choices(self):
          return self.choices

More like this

  1. Model field choices as a namedtuple by whiteinge 2 years, 1 month ago
  2. In page edit object links by punteney 5 years, 1 month ago
  3. Manager introspecting attached model by ubernostrum 5 years, 2 months ago
  4. Command Line Script Launcher by dakrauth 4 years, 10 months ago
  5. FieldsetForm by Ciantic 6 years, 1 month ago

Comments

tomzee (on December 29, 2007):

Here is a similar solution which allows you to pass dictionaries to the constructor, and inserts the key/value pairs into the choice-list in the same manner they are in the dictionaries.

class ChoiceMap:
    def __init__(self, *args, **entries):
        self.choices = []
        def add_choices(d):
            self.__dict__.update(arg)
            for key, val in d.iteritems():
                self.choices.append((key, val))
        for arg in args:
            if isinstance(arg, dict):
                add_choices(arg)
        add_choices(entries)
    def get_choices(self):
        return self.choices

#

(Forgotten your password?)