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):

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


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=[]):
    for child in node.children_list:
        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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s