Determine the type of an object? Determine the type of an object? python python

Determine the type of an object?


There are two built-in functions that help you identify the type of an object. You can use type() if you need the exact type of an object, and isinstance() to check an object’s type against something. Usually, you want to use isinstance() most of the times since it is very robust and also supports type inheritance.


To get the actual type of an object, you use the built-in type() function. Passing an object as the only parameter will return the type object of that object:

>>> type([]) is listTrue>>> type({}) is dictTrue>>> type('') is strTrue>>> type(0) is intTrue

This of course also works for custom types:

>>> class Test1 (object):        pass>>> class Test2 (Test1):        pass>>> a = Test1()>>> b = Test2()>>> type(a) is Test1True>>> type(b) is Test2True

Note that type() will only return the immediate type of the object, but won’t be able to tell you about type inheritance.

>>> type(b) is Test1False

To cover that, you should use the isinstance function. This of course also works for built-in types:

>>> isinstance(b, Test1)True>>> isinstance(b, Test2)True>>> isinstance(a, Test1)True>>> isinstance(a, Test2)False>>> isinstance([], list)True>>> isinstance({}, dict)True

isinstance() is usually the preferred way to ensure the type of an object because it will also accept derived types. So unless you actually need the type object (for whatever reason), using isinstance() is preferred over type().

The second parameter of isinstance() also accepts a tuple of types, so it’s possible to check for multiple types at once. isinstance will then return true, if the object is of any of those types:

>>> isinstance([], (tuple, list, set))True


You can do that using type():

>>> a = []>>> type(a)<type 'list'>>>> f = ()>>> type(f)<type 'tuple'>


It might be more Pythonic to use a try...except block. That way, if you have a class which quacks like a list, or quacks like a dict, it will behave properly regardless of what its type really is.

To clarify, the preferred method of "telling the difference" between variable types is with something called duck typing: as long as the methods (and return types) that a variable responds to are what your subroutine expects, treat it like what you expect it to be. For example, if you have a class that overloads the bracket operators with getattr and setattr, but uses some funny internal scheme, it would be appropriate for it to behave as a dictionary if that's what it's trying to emulate.

The other problem with the type(A) is type(B) checking is that if A is a subclass of B, it evaluates to false when, programmatically, you would hope it would be true. If an object is a subclass of a list, it should work like a list: checking the type as presented in the other answer will prevent this. (isinstance will work, however).