Hierarchical Structures in Python – i.e. folders

The method I found most appealing in dealing with hierarchical structures is a tree. I think is pretty straightforward and easy to implement and customize.
First we need a class that defines the nodes of the tree.

class Node:
    def __init__(self, name):
        self.children_list = []
        self.name_str = name

    def add_child(self, node):
        self.children_list.append(node)

This is the basic version of the node class. We are good to go. We have the two basic functions to create a new node and to store nodes as children thus building a hierarchy.

So, we build a root node…

root = Node("/")

then we create a second one

first_child = Node("first_child")

and append it to root

root.append(first_child)
    tree.append(node.name_str)

We could go on adding nodes (create node and append to other already existing node as child) to create a tree.

Now lets assume we have a nice tree and we want to return a json representation of the structure.
I (since I like to keep thinks seperated) would make a new file and import the node file.
This new file might look something like this:

def get_tree(node, tree=[]):
    tree.append(node.name_str)
    for child in node.children_list:
        subtree=[]
        tree.append(subtree)
        get_tree(child, subtree)
    return tree

So there you go, the programmers best friend recursion. This would return the tree as nested array containing a name and, if the node has children, an array of children. This structure could then be pickled or returned or stored.
To associate content with the folder there are several options. You could have a list of content objects similar to children_list or ids of content.

Advertisements