Identifying a class type - bad practice?

Ethan Furman ethan at stoneleaf.us
Tue Aug 18 15:08:42 EDT 2009


James Harris wrote:
> I am writing some code to form a tree of nodes of different types. The
> idea is to define one class per node type such as
> 
> class node_type_1(node):
>   <specific properties by name including other node types>
> class node_type_2(node):
>   <specific properties by name including other node types>
> etc
> 
> (Class "node" would hold any common properties).
> 
> When walking the tree I need to know what type of node I'm dealing
> with so polymorphism isn't generally useful. The action to be taken
> depends on the node type. Two options appear to be useful: __class__
> and isinstance. I know the latter will match the instance against any
> superclass and the former will match one class only.
> 
> My question is: is this the Pythonic way to deal with such a tree? Is
> there a better way? In C I would use structs where one field was a tag
> indicating the kind of struct.
> 
> James

I would recommend going with isinstance.  An instance of node_type_2 
will not be an instance node_type_1, so no worries there, and it leaves 
open the option of subclassing further if you need to later on.

~Ethan~



More information about the Python-list mailing list