Test if a class is inherited from another

Question:

This question is more Python related than Django related. I want to test write a test for this function that I am using to get a Django form dynamically with the fields I set.

def quiz_form_factory(question):
    properties = {
        'question': forms.IntegerField(widget=forms.HiddenInput, initial=question.id),
        'answers': forms.ModelChoiceField(queryset=question.answers_set)
    }
    return type('QuizForm', (forms.Form,), properties)

I want to test if, the QuizForm class returned is inherited from forms.Form.

Something like:

self.assertTrue(QuizForm isinheritedfrom forms.Form)  # I know this does not exist

Is there any way to do this?

Asked By: Renne Rocha

||

Answers:

Use issubclass(myclass, parentclass).

In your case:

self.assertTrue( issubclass(QuizForm, forms.Form) )
Answered By: pajton

Use the built-in issubclass function. e.g.

issubclass(QuizForm, forms.Form)

It returns a bool so you can use it directly in self.assertTrue()

Answered By: bradley.ayers
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.