Bubble Foundry


Types in Python

by Peter.

There are many great things going for Python but I find its type system to be rather wonky. Most people will direct you to use the type() function to determine types:

>>> type([])
<type 'list'>
>>> type([]) == type(list)
False
>>> type([]) == type(list())
True
>>> type([]).__name__ == 'list'
True

However, in everyday use isinstance() is much more useful:

>>> isinstance([], list)
True
>>> isinstance({}, dict)
True
>>> isinstance('', str)
True
>>> isinstance(u'', unicode)
True
>>> isinstance(True, bool)
True
>>> isinstance(0, int)
True
>>> isinstance(0.0, float)
True

And yes, str and unicode are different types. Some have proposed various complicated approaches to deal with duck-typing and the like, but I’m happy with isinstance(). If you need more information, I suggest checking out the types section of the Python documentation or using the types modules. Finally, Shalabh Chaturvedi has written a nice little guide called Python Types and Objects.