1

I have to get the type of a variable and when I type type(variable) I get this :

<class 'Mytable.models.User'>

And I would like to equal the type of a variable I mean I try to write this :

type(variable) == Mytable.models.User

but I got False.

Could you help me please ?

  • Possible duplicate of [Python check instances of classes](https://stackoverflow.com/questions/14549405/python-check-instances-of-classes) – Srdjan Cosic Sep 05 '19 at 13:14
  • Possible duplicate of [How to compare type of an object in Python?](https://stackoverflow.com/questions/707674/how-to-compare-type-of-an-object-in-python) – dirkgroten Sep 05 '19 at 13:31
  • Note enough info, but from what you posted this test should succeed (even if it's not the best way to do it - check the ìsinstance(obj, cls)` function), so it may be that you're suffering from this issue: http://python-notes.curiousefficiency.org/en/latest/python_concepts/import_traps.html#the-double-import-trap – bruno desthuilliers Sep 05 '19 at 13:44

2 Answers2

2

You need to import the class into the current file to do a comparrison like that. Maybe like this:

from Mytable.models import User
print(type(variable) == User)

or use isinstance():

from Mytable.models import User
print(isinstance(variable, User))

For string comparrison you could use this (but it is not so adviced):

print(variable.__class__.__name__)
print(variable.__class__.__name__ == 'Mytable.models.User')
Ralf
  • 16,086
  • 4
  • 44
  • 68
0

Classes or in general types don't have comparison implemented. To check if certain type matches, use is instead of ==:

type(variable) is Mytable.models.User
GwynBleidD
  • 20,081
  • 5
  • 46
  • 77