Back to main.

Calmcode Shorts

toposort.py logotoposort.py

Toposort is a great tool when you've got an a process with dependencies and you'd just like to unfold the order in which they should occur. You will first need to install it with pip.

python -m pip install toposort

Let's proceed by creating a dictionary of dependencies.

dependencies = {
    "scipy": {"numpy"},
    "scikit-learn": {"numpy", "scipy"},
    "human-learn": {"scikit-learn", "jupyter"}
}

Note that the values in this dictionary are sets, not lists! Given such a dictionary we can now use toposort to figure out in what order the installation tasks need to happen. We can also see if there's any tasks that can happen in parallel.

from toposort import toposort

list(toposort(dependencies))
# [{'jupyter', 'numpy'}, {'scipy'}, {'scikit-learn'}, {'human-learn'}]

In this case, "jupyter" and "numpy" can be installed first and in parallel. If you don't care about parallism then you might also be able to use another function from the package.

from toposort import toposort_flatten

toposort_flatten(dependencies)
# ['jupyter', 'numpy', 'scipy', 'scikit-learn', 'human-learn']

In this case we're talking about installing packages, but any process with dependencies can be unfurled with this package.


Back to main.