def topological_sort(source):
    """perform topo sort on elements.
    :arg source: list of ``(name, [list of dependancies])`` pairs
    :returns: list of names, with dependancies listed first
    """
pending = [(name, set(deps)) for name, deps in source]
emitted = []
while pending:
    next_pending = []
next_emitted = []
for entry in pending:
    name, deps = entry
deps.difference_update(emitted)
if deps:
    next_pending.append(entry)
else:
    yield name
emitted.append(name)
next_emitted.append(name)
if not next_emitted:
    raise ValueError('cyclic or missing dependancy detected: %r' % (
        next_pending,))
pending = next_pending
emitted = next_emitted
Python: сортировка списка зависимостей