96

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?

Asclepius
  • 57,944
  • 17
  • 167
  • 143
Renne Rocha
  • 1,235
  • 1
  • 9
  • 10

2 Answers2

155

Use issubclass(myclass, parentclass).

In your case:

self.assertTrue( issubclass(QuizForm, forms.Form) )
pajton
  • 15,828
  • 8
  • 54
  • 65
  • @bcdan really? It works for direct, indirect or virtual inheritance. – Bo. Dec 07 '15 at 13:32
  • 2
    @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 08 '15 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. – powderflask Jan 31 '16 at 01: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 '16 at 20:53
  • In version 3.7, i tested issubclass(C, A). It returned True. – Ashmoreinc Nov 13 '19 at 10:02
14

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

bradley.ayers
  • 37,165
  • 14
  • 93
  • 99