When to check an object type - Python isinstance example
Archive - Originally posted on "The Horse's Mouth" - 2016-11-03 19:47:22 - Graham EllisI'll encourage you not to look at an object in a Python program - or in any other OO langauge - you find out what type it is ... at least until you've thought about why you're doing it.
If you need to, you can look - you have the type function, you have the __class__.__name__ variable and you have isinstance.
Isinstance lets you check the hierarcy of an object - so I can use it to ask if an object is of a particular type, or a type that's based on it.
Here's a look to see if something's a list:
if isinstance(meal,list):
and in use in a program [here]. I'm not thrilled with the example - but is shows you the syntax. I would much rather you used polymorphism (several methods of the same name in order to decide internally how to print the data) rather than a branch chain based on the type.
Where I will encourage you to use isinstance is upon entry to a function that's called from outside your area of control - for example within the API of a function, method, module or package that you've written for others to use, and you want to check they're passing you sensible parameters. See [here] for an example.