Peter Julian
Peter Julian

Reputation: 41

The type of a variable

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 ?

Upvotes: 1

Views: 66

Answers (2)

GwynBleidD
GwynBleidD

Reputation: 20569

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

Upvotes: 0

Ralf
Ralf

Reputation: 16515

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

Upvotes: 2

Related Questions