DEV Community

Fernando Paladini
Fernando Paladini

Posted on

Model Directed and Undirected Graphs in Pure Python with Liasis-Graph

Prototyping task dependencies, state transitions, or small network topologies in Python often pushes teams between two awkward choices: pulling in a large scientific graph package for fifty lines of logic, or hand-rolling nested dictionaries whose directed and undirected rules silently drift apart. Worse, older lightweight graph utilities frequently point to test runners like nose that no longer import on Python 3.12 and newer.

TL;DR: Liasis-Graph (inside paladini/UFSC-graphs) is an MIT-licensed, zero-dependency Python module that models both undirected (digraph=False) and directed (digraph=True) graphs over dictionary-of-sets adjacency tables, enforcing mode boundaries via DigraphError and NotDigraphError. All 57 tests inherit from unittest.TestCase and run directly via python -m unittest. Always pass a fresh {} dictionary to Graph({}, digraph=...) to avoid a mutable default argument leak, and stick to core operations plus is_regular() and is_complete() unless you patch three documented bugs in its undirected traversal helpers.

In this tutorial, you will fetch the verified commit, build directed and undirected graphs with explicit mode checks, run the standard-library unittest suite without nose, and inspect the implementation boundaries before reusing the code.

Prerequisites and Environment Boundaries

Confirm these details before running the examples:

  • Source state and license: paladini/UFSC-graphs publishes no tagged releases or PyPI packages. All files live on master at commit c99b460 under the MIT License inside trabalho1/liasis-graph/.
  • Python runtime: Python 3.8 or newer (smoke-tested on Python 3.14.3). graph.py and graph_exceptions.py use only Python's standard library (random and unittest).
  • No nose installation required: README.md and makefile reference nosetests. Because nose 1.3.7 relies on standard-library symbols removed by Python 3.12 (imp), invoke unittest directly instead.

Minimal Working Path

Clone the repository at commit c99b4604c5eaf5949449430b6a07dc07b1e0b7ea and enter trabalho1/liasis-graph:

git clone https://github.com/paladini/UFSC-graphs.git
cd UFSC-graphs
git checkout c99b4604c5eaf5949449430b6a07dc07b1e0b7ea
cd trabalho1/liasis-graph
Enter fullscreen mode Exit fullscreen mode

If git is unavailable, download and extract the commit archive with Python's standard library:

import io, zipfile
from urllib.request import urlopen

sha = "c99b4604c5eaf5949449430b6a07dc07b1e0b7ea"
with urlopen(f"https://github.com/paladini/UFSC-graphs/archive/{sha}.zip", timeout=30) as resp:
    with zipfile.ZipFile(io.BytesIO(resp.read())) as archive:
        archive.extractall(".")
Enter fullscreen mode Exit fullscreen mode

From trabalho1/liasis-graph, run a script modeling a directed build pipeline alongside an undirected four-node ring topology. Notice that both Graph calls pass an explicit {} dictionary:

from graph import Graph
from graph_exceptions import DigraphError, NotDigraphError

pipeline = Graph({}, digraph=True)
for step in ("fetch", "validate", "publish", "notify"):
    pipeline.add(step)

pipeline.connect("fetch", "validate")
pipeline.connect("validate", "publish")
pipeline.connect("publish", "notify")
pipeline.connect("validate", "notify")

print("order:", pipeline.order())
print("validate out_degree:", pipeline.out_degree("validate"))
print("validate successors:", sorted(pipeline.sucessors("validate")))
print("notify in_degree:", pipeline.in_degree("notify"))
print("notify predecessors:", sorted(pipeline.predecessors("notify")))

ring = Graph({}, digraph=False)
for node in ("n1", "n2", "n3", "n4"):
    ring.add(node)
for a, b in (("n1", "n2"), ("n2", "n3"), ("n3", "n4"), ("n4", "n1")):
    ring.connect(a, b)

print("ring degree(n1):", ring.degree("n1"))
print("ring is_regular:", ring.is_regular())
print("ring is_complete:", ring.is_complete())

try:
    pipeline.degree("validate")
except DigraphError as exc:
    print("DigraphError caught:", exc)

try:
    ring.in_degree("n1")
except NotDigraphError as exc:
    print("NotDigraphError caught:", exc)
Enter fullscreen mode Exit fullscreen mode

Two upstream method names in graph.py are worth noting:

  • sucessors(vertex) uses a single c in both implementation and tests.
  • The module docstring mentions ajdacents_to(vertex), whereas the actual method on line 139 is adjacents_to(vertex).

Expected Result and Reproducible Verification

Running the script prints deterministic counts, neighbor lists, regularity checks, and explicit mode errors:

order: 4
validate out_degree: 2
validate successors: ['notify', 'publish']
notify in_degree: 2
notify predecessors: ['publish', 'validate']
ring degree(n1): 2
ring is_regular: True
ring is_complete: False
DigraphError caught: "Digraph doesn't implement Degree method.                 Take a look at in_degree(vertex) and out_degree(vertex)."
NotDigraphError caught: "Not directed graphs doesn't implement in_degree method."
Enter fullscreen mode Exit fullscreen mode

Next, run the directed graph suite (test_digraph.py):

python -m unittest test_digraph -v
Enter fullscreen mode Exit fullscreen mode

All 28 directed-graph tests pass:

test_is_complete (test_digraph.DerivedOperations.test_is_complete) ... ok
...
test_sucessors (test_digraph.TestBasicOperations.test_sucessors) ... ok

----------------------------------------------------------------------
Ran 28 tests in 0.001s

OK
Enter fullscreen mode Exit fullscreen mode

To run both test_digraph.py and test_not_digraph.py together:

python -m unittest discover -s . -p "test_*.py"
Enter fullscreen mode Exit fullscreen mode

Discovery executes 57 tests: 54 pass, and 3 fail in test_not_digraph.DerivedOperations (test_is_connected, test_is_tree, and test_transitive_closure), matching the unfinished status documented in graph.py and como_executar.txt. For HTML coverage without nose, install coverage in a virtual environment and run python -m coverage run -m unittest discover -s . -p "test_*.py" followed by python -m coverage html.

Why It Works

Liasis-Graph keeps its representation compact: self._vertices maps each vertex label to a set of outbound neighbor labels, while self._digraph controls edge symmetry and allowed operations.

  1. Guarded edge updates: connect(vertexA, vertexB) and disconnect(vertexA, vertexB) verify that both endpoints exist in self._vertices before modifying edges, preventing typos from creating stray nodes. Undirected graphs update both neighbor sets symmetrically; digraphs update only self._vertices[vertexA].
  2. Dangling-edge cleanup: remove(vertex) strips vertex from every remaining neighbor set before deleting self._vertices[vertex].
  3. Domain-specific exceptions: Undirected methods (degree, adjacents_to) raise DigraphError on digraphs, while directed queries (in_degree, out_degree, predecessors, sucessors) raise NotDigraphError on undirected graphs.
  4. Degree invariants: On undirected graphs, is_regular() checks that every vertex matches a sampled vertex's degree, and is_complete() checks that every vertex has degree order() - 1 (assuming no self-loops).

Failure Modes, Limitations, and Security Boundaries

Inspecting graph.py and the tests highlights five boundaries to handle before reusing Liasis-Graph:

  • Mutable default dictionary in Graph.__init__: Line 54 defines def __init__(self, vertices={}, digraph=False): and binds self._vertices = vertices. Because Python evaluates default arguments once at definition time, two Graph() calls without arguments share the same dictionary:
from graph import Graph

g1 = Graph()
g1.add("leaked")
g2 = Graph()
print(sorted(g2.vertices()))  # ['leaked']
Enter fullscreen mode Exit fullscreen mode

Always pass Graph({}, digraph=...), or change the signature locally to vertices=None with self._vertices = {} if vertices is None else vertices.

  • Three broken undirected traversal helpers: On digraphs, all derived methods raise NotImplementedError. On undirected graphs, transitive_closure, is_connected, and is_tree fail for three distinct reasons:
    1. __search_transitive_closure creates ft = set() and unions recursive calls without ever adding visited vertices to ft, always returning set().
    2. is_connected() checks self._vertices == transitive, comparing a dict against a set (False in Python; it needs set(self._vertices.keys()) == transitive).
    3. is_tree() calls self.__has_cicle_with(v, v, set()) with three arguments instead of four, loops over self.adjacents_to(vertex) rather than current_vertex, and calls bare __has_cicle_with(...) without self..
  • Empty-graph IndexError: Calling random() or is_regular() on an empty Graph({}) triggers IndexError: Cannot choose from an empty sequence inside random.choice(). Check graph.order() > 0 first.
  • Live set aliasing and duplicate test names: adjacents_to() and sucessors() return the internal set reference rather than .copy(), so mutating the result bypasses undirected edge symmetry. In addition, both test modules define test_random twice inside TestBasicOperations, shadowing the first definition.
  • Repository asset hygiene: trabalho1/liasis-graph/ also contains graph-fernando-paladini.tar.gz and static coverage output (tests_coverage/) bundling old jQuery 1.x files. Copy only graph.py and graph_exceptions.py into projects rather than unpacking legacy tarballs or serving tests_coverage/ over HTTP, and keep vertex keys limited to trusted hashable primitives (str, int, or tuple).

FAQ

Why does make test fail when nose is installed on Python 3.12+?
The makefile runs nosetests whenever it is found on PATH, which raises ModuleNotFoundError: No module named 'imp' on Python 3.12+. Run python -m unittest discover -s . -p "test_*.py" -v instead.

Why did connect("a", "b") leave the graph unchanged?
connect() ignores edges unless both "a" and "b" were already added with add() or supplied in the initial vertices dictionary.

Does Liasis-Graph support edge weights or parallel edges?
No. Neighbor collections are plain Python set instances, so edges are unweighted and duplicates collapse automatically.

Takeaway

Liasis-Graph offers a concise pure-Python blueprint for adjacency-set graphs and mode-safe DigraphError / NotDigraphError checks when you pass an explicit {} to Graph(), run its 57 tests via python -m unittest, and steer clear of its unfinished DFS helpers.

When you need a small dependency or topology graph in Python without heavy external packages, do you build a focused adjacency-set class with unittest checks or reach for graphlib and networkx?

Disclosure: This tutorial was researched, smoke-tested on Python 3.14, and drafted with AI assistance using primary repository sources and local unit test verification.

Top comments (0)