Python Glossary Русский

Python 3.9+graphlibexception

graphlib.CycleError

topological sorting

Raised by TopologicalSorter when the graph contains a cycle; its second argument holds the cycle as a list of nodes.

Syntax

except graphlib.CycleError as e: cycle = e.args[1]

It subclasses ValueError, so except ValueError catches it too. The cycle lives in e.args[1] rather than a dedicated attribute, and the first node repeats at the end: ['a', 'b', 'a']. Only one cycle is reported, not all of them; a node that depends on itself is a cycle as well.

Examples

from graphlib import TopologicalSorter, CycleError
try:
    list(TopologicalSorter({'a': {'b'}, 'b': {'a'}}).static_order())
except CycleError as e:
    print(e.args[1])  # → ['a', 'b', 'a']
print(issubclass(CycleError, ValueError))  # → True

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy