tedtoy
tedtoy

Reputation: 178

How can I dynamically create objects in django/python?

In my code I have many if/elif statements like this:

if type == "cat":
    vote = VoteCat (
        user = user,
        cat_id = thing_id )
    vote.save()
elif type == "dog":
    vote = VoteDog (
        user = user,
        dog_id = thing_id )
    vote.save()

What would be a good way to change my code to get rid of the if statements and instantiate the object I need dynamically? The code I am hoping I can write would accomplish the same as above but look more like this:

AnimalVote = get_animalvote_by_type(type)
AnimalVote.user = user
AnimalVote.assign_animal_id(thing_id)
AnimalVote.save()

Upvotes: 3

Views: 1427

Answers (2)

Marcin
Marcin

Reputation: 49816

The simplest translation is:

types = dict('cat' = CatType, 'dog' = DogType)
newobj = types[type](user = user, cat_id = thing_id)

Obviously, this relies on the types taking the same parameters.

Upvotes: 7

David Z
David Z

Reputation: 131550

Classes in Python are objects, so you can just have a map mapping names to classes:

animal_type_map = {'cat': VoteCat, 'dog': VoteDog}

Then you can use animal_type_map[type] just as you would use VoteCat or VoteDog.

Upvotes: 3

Related Questions