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-graphspublishes no tagged releases or PyPI packages. All files live onmasterat commitc99b460under the MIT License insidetrabalho1/liasis-graph/. - Python runtime: Python 3.8 or newer (smoke-tested on Python 3.14.3).
graph.pyandgraph_exceptions.pyuse only Python's standard library (randomandunittest). - No
noseinstallation required:README.mdandmakefilereferencenosetests. Becausenose1.3.7 relies on standard-library symbols removed by Python 3.12 (imp), invokeunittestdirectly 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 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(".") 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) Two upstream method names in graph.py are worth noting:
-
sucessors(vertex)uses a singlecin both implementation and tests. - The module docstring mentions
ajdacents_to(vertex), whereas the actual method on line 139 isadjacents_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." Next, run the directed graph suite (test_digraph.py):
python -m unittest test_digraph -v 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 To run both test_digraph.py and test_not_digraph.py together:
python -m unittest discover -s . -p "test_*.py" 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.
- Guarded edge updates:
connect(vertexA, vertexB)anddisconnect(vertexA, vertexB)verify that both endpoints exist inself._verticesbefore modifying edges, preventing typos from creating stray nodes. Undirected graphs update both neighbor sets symmetrically; digraphs update onlyself._vertices[vertexA]. - Dangling-edge cleanup:
remove(vertex)stripsvertexfrom every remaining neighbor set before deletingself._vertices[vertex]. - Domain-specific exceptions: Undirected methods (
degree,adjacents_to) raiseDigraphErroron digraphs, while directed queries (in_degree,out_degree,predecessors,sucessors) raiseNotDigraphErroron undirected graphs. - Degree invariants: On undirected graphs,
is_regular()checks that every vertex matches a sampled vertex's degree, andis_complete()checks that every vertex has degreeorder() - 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 definesdef __init__(self, vertices={}, digraph=False):and bindsself._vertices = vertices. Because Python evaluates default arguments once at definition time, twoGraph()calls without arguments share the same dictionary:
from graph import Graph g1 = Graph() g1.add("leaked") g2 = Graph() print(sorted(g2.vertices())) # ['leaked'] 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, andis_treefail for three distinct reasons:-
__search_transitive_closurecreatesft = set()and unions recursive calls without ever adding visited vertices toft, always returningset(). -
is_connected()checksself._vertices == transitive, comparing adictagainst aset(Falsein Python; it needsset(self._vertices.keys()) == transitive). -
is_tree()callsself.__has_cicle_with(v, v, set())with three arguments instead of four, loops overself.adjacents_to(vertex)rather thancurrent_vertex, and calls bare__has_cicle_with(...)withoutself..
-
- Empty-graph
IndexError: Callingrandom()oris_regular()on an emptyGraph({})triggersIndexError: Cannot choose from an empty sequenceinsiderandom.choice(). Checkgraph.order() > 0first. - Live set aliasing and duplicate test names:
adjacents_to()andsucessors()return the internalsetreference rather than.copy(), so mutating the result bypasses undirected edge symmetry. In addition, both test modules definetest_randomtwice insideTestBasicOperations, shadowing the first definition. - Repository asset hygiene:
trabalho1/liasis-graph/also containsgraph-fernando-paladini.tar.gzand static coverage output (tests_coverage/) bundling old jQuery 1.x files. Copy onlygraph.pyandgraph_exceptions.pyinto projects rather than unpacking legacy tarballs or servingtests_coverage/over HTTP, and keep vertex keys limited to trusted hashable primitives (str,int, ortuple).
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.
