Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursion over a list of lists without isinstance()

I have just read "isinstance() considered harmful", and it seems reasonable. In short, it argues for avoiding the use of this function.

Well, just now I happen to be writing a program which takes inputs structured as a tree, and needs the tree's structure information. Without time to implement a GUI, I impose on the user to write it to a configuration file (I know this is a bad interface, but the schedule is really tight). My users are very technical, but don't necessarily know python. I chose that the file will contain lists of lists (of lists of lists etc) representing the input trees, with the final elements being the leaf nodes of the trees. I think this is much better than imposing the synthax of dictionaries on users.

I plan to parse the lists recursively as the following (ommiting the use of the tree's structure, let's simplify and say treatLeafNode() must be called on each leaf node):

def parseTree(input):
    if isinstance (input, list):
        for item in input:
            parseTree(item)
    else:
        treatLeafNode(item)

In light of the article, I'm wondering if there is a simple way to recurse over that without using isinstance()...

Does anyone know one?

like image 286
Emilio M Bumachar Avatar asked May 04 '11 11:05

Emilio M Bumachar


2 Answers

Your situation is one of those where I would use isinstance. Your data structure is well-constrained, and you need to distinguish between a list and not a list. Use isinstance to ask if it is a list. You don't say, but I imagine strings might be among the leaves of your tree, and they are iterable as lists are, so it's fiddly to distinguish between them in duck-typing ways.

like image 185
Ned Batchelder Avatar answered Oct 22 '22 18:10

Ned Batchelder


You could use

def parseTree(input):
    try:
        for item in input:
            parseTree(item)
    except TypeError:
        treatLeafNode(item)

Note that this will also iterate over strings though.

like image 5
Sven Marnach Avatar answered Oct 22 '22 18:10

Sven Marnach