98

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?

0

2 Answers 2

160

Use issubclass(myclass, parentclass).

In your case:

self.assertTrue( issubclass(QuizForm, forms.Form) )
5
  • @bcdan really? It works for direct, indirect or virtual inheritance.
    – Bo.
    Dec 7, 2015 at 13:32
  • 3
    @Bo. I tested it with subclasses. if class A, class B(A), and class C(B), C.issubclass(A) returns False. I might have gotten terminology incorrect, but I'm just saying this technicality doesn't work for completeness of the answer.
    – bcdan
    Dec 8, 2015 at 14:11
  • 8
    Old thread, but for completeness: bcdan is not correct. At least in Python 3.x, the example he gives above returns True, as indicated by the docs. Jan 31, 2016 at 1:54
  • 4
    @bcdan the way to do it is issubclass(C, A). I did this on Python 2.7, and it worked with both new and old style classes.
    – Gamrix
    May 26, 2016 at 20:53
  • In version 3.7, i tested issubclass(C, A). It returned True.
    – Ashmoreinc
    Nov 13, 2019 at 10:02
15

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()

Not the answer you're looking for? Browse other questions tagged or ask your own question.