def toposort(G):
    """Returns the topological sort of the input graph G.

    The algorithm toposort is described in Cormen, Leiserson, Rivest,
    *Introduction to Algorithms* [CLR].  The code here is explicitly
    modeled on their pseudocode.
    
    David Eppstein's PADS library employs an alternative strategy of
    'shadowing' the Searcher class methods via inheritance
    (http://www.ics.uci.edu/~eppstein/PADS/DFS.py).  His strategy
    makes the preorder, postorder, and backedge events more explicit
    than the implicit usage presented here based on coloring changes.
    """

    ordering = deque()
    seen = set()
    coloring = dict()

    @consumer
    def finishing(order):
        """Returns the vertices in the reverse of their finishing time.

        This function is implemented as a coroutine so that it can be
        decoupled from the actual setting of the vertice's color in
        the DFS. So the only protocol that requires agreement is this
        marking of a coloring.

        It's critical that this function be decorated with the
        @consumer decorator so that it's advanced to waiting on any
        data.
        """

        while True:
            v, old_color, new_color = (yield)
            if new_color == BLACK:
                order.appendleft(v)

    with observation(observe=coloring,
                     notify=[finishing(ordering)]) as coloring:
        for v in DFS(G, coloring):
            # In this code, the real work is in the finishing
            # function.  For now, we will just verify that the vertex
            # is touched at *most* once.
            assert(v not in seen)
            seen.add(v)

    # Now verify that each vertex was touched at *least* once
    assert(seen == set(vertices(G)))
        
    return ordering
Returns the topological sort of the input graph G.

    The algorithm toposort is described in Cormen, Leiserson, Rivest,
    *Introduction to Algorithms* [CLR].  The code here is explicitly
    modeled on their pseudocode.
    
    David Eppstein's PADS library employs an alternative strategy of
    'shadowing' the Searcher class methods via inheritance
    (http://www.ics.uci.edu/~eppstein/PADS/DFS.py).  His strategy
    makes the preorder, postorder, and backedge events more explicit
    than the implicit usage presented here based on coloring changes.
    
recipes/Python/498260_Examples_algorithm_compositiobserver_pattern/recipe-498260.py