isinstance() and type() equivelence failure due to import mechanism (python/django)

4k views Asked by At

In a Django project I'm working on I import a form in the view as follows

#views.py
from forms import SomeForm

then in a test file I have

#form_test.py
from app.forms import SomeForm    
.
.
.
self.assertTrue(isinstance(response.context['form'], SomeForm))

Why doesn't the isinstance work?

If I inspect the output of type() for the two objects I get this:

response.context form: Expected form:

I can fix this by making my import mechanism in views.py match that in the form_test.py, but this seems like the wrong approach.

for reference, file structure as follows:

  • site/
    • manage.py
    • app/
      • forms.py
      • views.py
      • tests/
        • form_test.py
2

There are 2 answers

0
amirouche On BEST ANSWER

isinstance also compare module location, response.context['form'] class' module is forms where SomeForm module is app.forms you check this by inspecting respectively __class__.__module__ and __module__.

To make isinstance work you can:

  • fix the import in the views.py (recommended)
  • alter sys.path in form_testse.py to be able to import the form as from forms import SomeForm
  • try intrapackage references
0
eqzx On

one possible hack is to check the __name__ attribute of the types, although unless you fix it the Right way, you might run into other issues

def sharetypename(obj1, obj2):
    if isinstance(obj1, type):
        c1 = obj1.__name__
    else:
        c1 = type(obj1).__name__

    if isinstance(obj2, type):
        c2 = obj2.__name__
    else:
        c2 = type(obj2).__name__

    return c1 == c2