Skip to main content

A lightweight Python library to create and manipulate object-oriented graphs.

Project description

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.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pygraph_tool-2.0.0.tar.gz (19.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pygraph_tool-2.0.0-py3-none-any.whl (26.9 kB view details)

Uploaded Python 3

File details

Details for the file pygraph_tool-2.0.0.tar.gz.

File metadata

  • Download URL: pygraph_tool-2.0.0.tar.gz
  • Upload date:
  • Size: 19.3 kB
  • Tags: Source
  • Uploaded using 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}

File hashes

Hashes for pygraph_tool-2.0.0.tar.gz
Algorithm Hash digest
SHA256 00abc034027955cc13256025da683cce5645d1f6ced0987ccd61e5f558e4397a
MD5 6ce9e887091df7ef97533c68841dbffc
BLAKE2b-256 877f826fc5891b63a2a05abc0e728a48975c3f6ebf8d20753bf05121f345171b

See more details on using hashes here.

File details

Details for the file pygraph_tool-2.0.0-py3-none-any.whl.

File metadata

  • Download URL: pygraph_tool-2.0.0-py3-none-any.whl
  • Upload date:
  • Size: 26.9 kB
  • Tags: Python 3
  • Uploaded using 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}

File hashes

Hashes for pygraph_tool-2.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 e27a5211ed9cc42c8744bfcce7c10f0ffcbd07458d674e548f82397f9c976dc6
MD5 d9fc66cba04c20a62bf8fa7e0484a518
BLAKE2b-256 494dfeb0747063b1d407469c30186fda0f0007f1a95ae4bb90727b8d2efdf682

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page