views:

65

answers:

1

Hey guys!

So, I'm writing something and I've come into a roadblock on how to do it (and what is the proper way of doing things). SO, explaining the situation will help be better understand the problem, and hopefully someone will know the answer :) Here it goes:

Basically, I'm writing up some dynamic forms in Python (more specifically Django) - I am using a form factory to generate the form that I want to make. This is all fine and dandy, so far I have been defining the properties of the form in a hardcoded way, basically matching a property to a certain form (a ChoiceField, a Boolean, etc). BUT, what I would like instead of hardcoding these values is essentially create a properties dictionary dynamically, based on what information I pass it...

I basically have an array of "options", and so here are the two methods I am considering:

  1. Have a function for my "options" model/object that will have a series of if/elses. Like:
def get_property():
    if value = "artifact": #artifact being one option
        return form.BooleanField(label="blah")
    else if value = "environment": #environment being another type of option
        return form.ChoicesField(label="blah")
    etc...
  1. Use a very polymorphic approach. In this way, I mean creating an object based on my "option" object, and will create a new object based on the option. Say maybe something like:
class Base_Property():
    value = ""
    def __init__(self, option):
        value = form.BooleanField()

class Artifact_Property(Base_Property):
    def __init__(self, option):
        Base_Property.__init__(self, option)
        value = form.ChoiceField(choices=some_choices_array())

If option two is the way to go, could someone explain how I can create an object dynamically based on a variable? Like, matching the name of the value (say, Artifact, to match Artifact_Property).

Thanks so much for the help! I am really interested to see what happens to be a proper way - maybe it will spark a debate :)

-Shawn

+5  A: 

Have you considered using a dictionary? They're excellent for this sort of conditional.

def get_option(field_type):
    options = {
        'artifact': forms.BooleanField,
       'environment': forms.Choice Field,
    }

return options[field_type](label='blah')
Daniel Roseman
Excellent, had the same idea and had to try if actually works. It does.
Matti
I do like this, essentially a nicer version of my first option without using ifs. So far this is the front runner :)
shawnjan
+1 : simpler is better and easier to read/maintain
Ghislain Leveque