Skip to main content

pygraph-tool

pygraph-tool is a lightweight Python library to create, manipulate, traverse and filter object-oriented graphs.

It provides simple and explicit Python classes and methods for working with nodes and edges. Nodes and edges have stable identifiers, can store user-defined Python values, and can be annotated with metadata for filtering, categorization, layering or application-specific usage.

The library is designed for developers who need a small, readable, in-memory graph toolkit that can be used in many kinds of Python projects.

Why pygraph-tool?

pygraph-tool focuses on local graph manipulation with Python objects.

It is useful when you want to:

  • create graphs in memory,
  • store rich Python values in nodes and edges,
  • model directed or bidirectional relationships,
  • traverse graph structures,
  • retrieve neighbors, predecessors and successors,
  • extract local subgraphs,
  • filter graph elements by predicate or metadata,
  • write readable chained queries,
  • prototype graph-based systems without adding a heavy dependency.

pygraph-tool is not a graph database. It does not provide database-style persistence, transactions, clustering, query optimization or server features. It focuses on local, in-memory graph manipulation with lightweight dictionary and JSON import/export helpers.

Installation

Install from PyPI:

pip install pygraph-tool

With uv:

uv add pygraph-tool

Quick example

This example models a very small finite state machine.

from pygraph_tool import Graph, Metadata

graph: Graph[str, str] = Graph()

graph.add_node(
    value="Idle",
    node_id="idle",
    metadata=Metadata(categories={"state"}),
)

graph.add_node(
    value="Running",
    node_id="running",
    metadata=Metadata(categories={"state"}),
)

graph.add_unidirectional_edge(
    node_id_start="idle",
    node_id_end="running",
    edge_id="start",
    value="START",
    metadata=Metadata(categories={"transition"}),
)

successors = graph.get_successors("idle")

print([node.node_id for node in successors])

Output:

['running']

Chained queries

pygraph-tool also provides chainable query helpers for more readable graph operations.

states = (
    graph.query()
    .nodes()
    .with_category("state")
    .to_list()
)

You can start from a node and traverse the graph:

reachable_states = (
    graph.query()
    .from_node("idle")
    .traverse(max_depth=2, direction="outgoing", include_start=True)
    .to_list()
)

You can also query edges:

transitions = (
    graph.query()
    .edges()
    .with_category("transition")
    .to_list()
)

Main features

  • Directed and bidirectional edges
  • Automatic UUID-based identifiers when no id is provided
  • User-defined values on nodes and edges
  • Mutable node and edge values
  • Optional metadata on nodes and edges
  • Fast lookup by node and edge identifiers
  • Successor and predecessor traversal
  • Neighbor retrieval by direction
  • Reachability traversal with maximum depth
  • Unweighted shortest path search
  • Incoming, outgoing and incident edge retrieval
  • Subgraph extraction from selected nodes
  • Chainable local query interface
  • Generic filtering with predicates
  • Metadata-based filtering
  • Conversion to and from standard Python dictionaries
  • JSON serialization and deserialization
  • JSON file import and export
  • Optional value hooks for non-JSON values
  • Dedicated exceptions for graph, node and edge errors
  • Type information through py.typed

Use cases

pygraph-tool can be used for many graph-based needs, including:

  • finite state machines,
  • dependency graphs,
  • workflow graphs,
  • object relationship graphs,
  • concept maps,
  • knowledge graphs,
  • graph-based simulations,
  • educational examples,
  • local graph-based prototypes,
  • in-memory graph manipulation.

The library intentionally stays general-purpose. More specialized systems can be built on top of it without making the core package specific to one domain.

Documentation

More detailed documentation is available in the docs/ directory:

Public classes

pygraph-tool intentionally exposes only a few classes. You only ever import these:

from pygraph_tool import Edge, Graph, Metadata, Node

And the exceptions:

from pygraph_tool import (
    PyGraphToolException,
    GraphException,
    NodeException,
    EdgeException,
    SerializationException,
)

Everything else is internal. The fluent query helpers are reached through graph.query() and return internal objects that you never import or construct yourself, so there is very little to learn.

Common methods

Create graph elements:

graph.add_node(...)
graph.add_unidirectional_edge(...)
graph.add_bidirectional_edge(...)

Retrieve graph elements:

graph.get_node(...)
graph.get_edge(...)
graph.is_node(...)
graph.is_edge(...)

Traverse the graph:

graph.get_successors(...)
graph.get_predecessors(...)
graph.get_neighbors(...)
graph.get_reachable_nodes(...)
graph.get_shortest_path(...)

Retrieve connected edges:

graph.get_outgoing_edges(...)
graph.get_incoming_edges(...)
graph.get_incident_edges(...)

Filter graph elements:

graph.filter_nodes(...)
graph.filter_edges(...)
graph.filter_nodes_by_metadata(...)
graph.filter_edges_by_metadata(...)

Extract subgraphs:

graph.extract_subgraph(...)

Use chained queries:

graph.query().nodes()
graph.query().edges()
graph.query().from_node(...)

Import and export graphs:

graph.to_dict()
graph.to_json(...)
graph.save_json(...)
Graph.from_dict(...)
Graph.from_json(...)
Graph.load_json(...)

Development

Install development dependencies:

uv sync --dev

Run the main checks:

uv run ruff format .
uv run ruff check .
uv run mypy pygraph_tool
uv run coverage run --branch -m pytest
uv run coverage report -m

More details are available in the development guide.

Contributing

Contributions are welcome. Please read CONTRIBUTING.md before opening an issue or a pull request.

Security

If you need to report a security issue, please read SECURITY.md.

Versioning

pygraph-tool follows semantic versioning.

Given a version number MAJOR.MINOR.PATCH:

  • MAJOR changes may introduce breaking changes.
  • MINOR changes add functionality in a backward-compatible way.
  • PATCH changes fix bugs in a backward-compatible way.

Roadmap

Potential future improvements:

  • Optional local storage helpers
  • Public indexing system
  • Weighted shortest path search
  • Mermaid export
  • Graph visualization helpers
  • Additional graph traversal utilities

License

This project is licensed under the terms of the MIT License.

Author

Created and maintained by David BEL AICH.

For questions or suggestions, please contact: belaich.david@outlook.fr.

Metadata

Release files for pygraph-tool 2.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pygraph-tool 2.0.0
File Size Uploaded Provenance Actions
pygraph_tool-2.0.0.tar.gz 19.3 kB Without provenance Details for pygraph_tool-2.0.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pygraph-tool 2.0.0
File Interpreter ABI Platform Actions
pygraph_tool-2.0.0-py3-none-any.whl Python 3 none any Details for pygraph_tool-2.0.0-py3-none-any.whl

Total release size: 46.2 kB

Release files / pygraph_tool-2.0.0.tar.gz

Download URL pygraph_tool-2.0.0.tar.gz
Size 19.3 kB
Tags Source
SHA-256 checksum
How to use checksums
00abc034027955cc13256025da683cce5645d1f6ced0987ccd61e5f558e4397a
BLAKE2b-256 checksum
How to use checksums
877f826fc5891b63a2a05abc0e728a48975c3f6ebf8d20753bf05121f345171b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.11.3 {"installer":{"name":"uv","version":"0.11.3","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release files / pygraph_tool-2.0.0-py3-none-any.whl

Download URL pygraph_tool-2.0.0-py3-none-any.whl
Size 26.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
e27a5211ed9cc42c8744bfcce7c10f0ffcbd07458d674e548f82397f9c976dc6
BLAKE2b-256 checksum
How to use checksums
494dfeb0747063b1d407469c30186fda0f0007f1a95ae4bb90727b8d2efdf682
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.11.3 {"installer":{"name":"uv","version":"0.11.3","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Security for pygraph-tool 2.0.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page