views:

485

answers:

2

I have an class that has a list of "dependencies" pointing to other classes of the same base type.

class Foo(Base):
    dependencies = []

class Bar(Base):
    dependencies = [Foo]

class Baz(Base):
    dependencies = [Bar]

I'd like to sort the instances these classes generate based on their dependencies. In my example I'd expect instances of Foo to come first, then Bar, then Baz.

What's the best way to sort this?

+10  A: 

It's called a topological sort.

def sort_deps(objs):
    queue = [objs with no dependencies]
    while queue:
        obj = queue.pop()
        yield obj
        for obj in objs:
            if dependencies are now satisfied:
                queue.append(obj)
    if not all dependencies are satisfied:
        error
    return result
Dietrich Epp
+3  A: 

I had a similar question just last week - wish I'd know about Stack Overflow then! I hunted around a bit until I realized that I had a DAG (Directed Acyclic Graph since my dependencies couldn't be recursive or circular). Then I found a few references for algorithms to sort them. I used a depth-first traversal to get to the leaf nodes and add them to sorted list first.

Here's a page that I found useful:

Directed Acyclic Graphs

Cincinnati Joe
Interesting... but no links to these other resources. Can you provide some of the links to complete the answer to this question?
S.Lott
I added a link above. Being new, it would only let me include one in my post, so here's another that has some good background: http://www.codeproject.com/KB/java/BFSDFS.aspx
Cincinnati Joe
Thanks, the link you provided in your answer is pretty good. I just wish these university types could actually insert a real graphic once in a while rather than ansi art. hehe
Soviut