Python Graphlib Module prepare()














































Python Graphlib Module prepare()



In the previous article, we have discussed about 

add(node*predecessors)



In this article ,we are going to discuss some more methods in graphlib module



 prepare()
 This  Method is used to mark the graphs as finished and check for cycles in   the  graph.    
Example:
from graphlib import TopologicalSorter
ts = TopologicalSorter()
ts.add(4, 2, 5)
ts.add(1, 0)
ts.prepare()

->If any error is detected, CycleError will be raised.
Example:
from graphlib import TopologicalSorter
  
ts = TopologicalSorter()
  
ts.add(3, 2, 1)
ts.add(1, 0)
ts.add(0,1)
ts.prepare()
print([*ts.static_order()])
error:

Traceback (most recent call last):
  File "C:Users indmAppDataLocalProgramsPythonPython39graphlib.py", line 9, in <module>
    ts.prepare()
  File "C:Users indmAppDataLocalProgramsPythonPython39libgraphlib.py", line 104, in prepare
    raise CycleError(f"nodes are in a cycle", cycle)
graphlib.CycleError: ('nodes are in a cycle', [1, 0, 1])

->After a call to this function, the graph cannot be modified, and we cannot added more nodes by using add() method.

Example:
from graphlib import TopologicalSorter
  
ts = TopologicalSorter()
ts.add(7, 8, 2)
ts.add(1, 0)
ts.prepare()
ts.add(3,4)
print([*ts.static_order()])
error:
Traceback (most recent call last):
  File "C:Users indmAppDataLocalProgramsPythonPython39graphlib.py", line 10, in <module>
    ts.add(3,4)
  File "C:Users indmAppDataLocalProgramsPythonPython39libgraphlib.py", line 73, in add
    raise ValueError("Nodes cannot be added after a call to prepare()")
ValueError: Nodes cannot be added after a call to prepare()





Comments