object instance / type / typeof

Posted: March 10th, 2010 | Author: Davo | Filed under: Django | Tags: , , , | 1 Comment »

In some circumstances it is useful to know what type() / instance the object is.
Python provides 2 useful built in functions which can be handy for this kind of operations.

>>> from apps.deals.models import Deal
>>> deal = Deal.objects.get(id=1)
>>> type(deal).__name__ # retrieve the name of the class
'Deal'
>>> type(Deal()).__name__ # same
'Deal'
>>> type(str()).__name__ # internal python string class.
'str'

Now lets see how the isinstance() works

>>> isinstance(deal, str) # is 'deal' instance of 'str' ?
False
>>> isinstance(deal, Deal) # is 'deal' instance of Deal ?
True
>>>