"You can't put on your shoes before your socks. Topological sort is the algorithm that, given a tangle of 'X must come before Y' rules, hands you a valid order to do everything — or tells you the rules contradict themselves."
The Problem
A topological order linearizes a DAG so every prerequisite appears before its dependents. It directly models build dependencies, prerequisites, task scheduling, and spreadsheet recalculation. Python import execution also involves runtime code, caching, and circular-import behavior, so it is not simply one global topological sort.
Kahn's Algorithm: Peel Off the Ready Ones
The most intuitive method works by in-degree — how many prerequisites each node still has unmet. Repeatedly: take any node with zero remaining prerequisites (it's ready to go), output it, and remove its outgoing edges (decrementing its neighbors' in-degrees, possibly making them ready too). Use a queue to hold the ready nodes. Keep going until everything's output. It's BFS-flavored: process the frontier of currently-doable tasks, which unlocks the next frontier. O(V + E).
DFS postorder is another standard method, but it must track unvisited, active, and finished states. Encountering an active node detects a cycle. Reversing postorder without cycle detection can produce a plausible but invalid result for a non-DAG.
The Bonus: Cycle Detection
Topological sort only works on a DAG — a graph with no cycles. And it tells you when that's violated: in Kahn's algorithm, if you run out of zero-in-degree nodes before outputting them all, the leftover nodes form a cycle (a mutual dependency: A needs B, B needs A — neither can ever be 'ready'). That's a real, useful diagnostic: a build system reporting "circular dependency detected" is a failed topological sort. So the algorithm doesn't just order the doable — it proves whether a valid order exists at all.