This snippet defines 3 functions to create in a few seconds an image of
a graph containing arbitrary python objects. It uses the module pygraphviz
(available at

See the example use case at the end of the module.

# module fastgraph
# created by Gribouillis for the python forum at
# November 9, 2010
# Licence: public domain

"""This module defines 3 functions (node, edge and graph) to help
create a graph (a pygraphviz.AGraph instance) linking arbitrary
python objects.

This graph can be saved in various image formats, and in dot format.

import pygraphviz

def node(x):
    "helper to create graphs"
    return (x,)

def edge(x, y):
    "helper to create graphs"
    return (x, y)

def graph(items, tolabel, **kwd):
    """Create a pygraphviz AGraph instance

    @ items - a sequence of node(obj), or edge(obj, obj) items (obj can be any python object)
    @ tolabel - a function tolabel(obj) -> str which converts an object to string
    @ **kwd - additional keyword arguments for AGraph.__init__
    names = dict()
    the_graph = pygraphviz.AGraph(**kwd)
    for uple in (tuple(t) for t in items):
        for obj in uple:
            if not obj in names:
                names[obj] = "n%d" % len(names)
                the_graph.add_node(names[obj], label=tolabel(obj), shape="box")
        if len(uple) == 2:
            the_graph.add_edge(*(names[obj] for obj in uple))
    return the_graph

if __name__ == "__main__":
    def my_items():
        """Exemple generator of graph items. Our graph contains string here"""
        for x in "abcde":
            yield node(x)
        for s in "ab ac bd ea da".split():
            x, y = iter(s)
            yield edge(x, y)
    def my_label(x):
        "Create a label for graph objects"
        return x.upper()
    g = graph(my_items(), my_label)
    g.draw('mygraph.png', prog='circo') # prog can be neato|dot|twopi|circo|fdp|nop