Pythonic use of the isinstance function?
- by Pace
Whenever I find myself wanting to use the isinstance() function I usually know that I'm doing something wrong and end up changing my ways. However, in this case I think I have a valid use for it. I will use shapes to illustrate my point although I am not actually working with shapes. I am parsing XML configuration files that look like the following:
<square>
<width>7</width>
</square>
<rectangle>
<width>5</width>
<height>7</height>
</rectangle>
<circle>
<radius>4</radius>
</circle>
For each element I create an instance of the Shape class and build up a list of Shape objects in a class called the ShapeContainer. Different parts of the rest of my application need to refer to the ShapeContainer to get certain shapes. Depending on what the code is doing it might need just rectangles, or it might operate on all quadrangles, or it might operate on all shapes. I have created the following function in the ShapeContainer class (the actual function uses a list comprehension but I have expanded it here for readability):
def locate(self, shapeClass):
result = []
for shape in self.__shapes:
if isinstance(shape,shapeClass):
result.append(shape)
return result
Is this a valid use of the isinstance function? Is there another way I can do this which might be more pythonic?