Is using Python `isinstance` ever right?

dynamic, instance, oop, python

Solution

Your example seems like a legitimate use case of `isinstance()`.

It's not that `isinstance()` is bad, often polymorphism can be used for the same purpose (which results in cleaner code in where the class is used).

But sometimes, `isinstance()` is what you need. For example, the pythonic way of detecting whether a variable is string or not is `isinstance(var, basestring)`.

Problem

I've got a 2D array of different blocks, all inheriting from Block. I want to check if the block that I clicked on is a Dirt type block, like this: ``` clickedblock = getClickedBlock() if isinstance(clickedblock, Dirt): place a block else: don't place a block ``` I've heard that `isinstance` is bad, and should be avoided because it creates forks in code. What times would `isinstance` be good to use? Another more cumbersome solution for my problem would be to have a field of Block called 'id' and then check if it equals some constant that means Dirt. But that sounds quite bad and more prone for mistake than the simple `isinstance`.

Original source