Check if a class is inherited from another

This question is more related to Python than related to Django. I want to test a test record for this function, which I use to dynamically get a Django form 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 check if the QuizForm class returns 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?

+45
python unit-testing
Apr 11 2018-11-11T00:
source share
4 answers

Use issubclass (myclass, parentclass) .

In your case:

 self.assertTrue( issubclass(QuizForm, forms.Form) ) 
+72
Apr 11 2018-11-11T00:
source share

All you have to do is use issubclass :

 self.assertTrue(issubclass(QuizForm, forms.Form)) 
+5
Apr 11 2018-11-11T00:
source share

Use the built-in issubclass function. eg.

 issubclass(QuizForm, forms.Form) 

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

+4
Apr 11 2018-11-11T00:
source share

Check out issubclass(subclass,baseclass) inline method. This should be exactly what you need.

+2
Apr 11 2018-11-11T00:
source share



All Articles