Skip to main content

SPARQLKit

This package provides parsers and serializers for the SPARQL 1.1 Query Language.

Note: This is not a SPARQL processing engine.

Install

pip install sparqlkit

For CLI support:

pip install sparqlkit[cli]

CLI

SPARQLKit provides a command-line interface for formatting SPARQL files.

sparql --help
sparql -h

Commands

format

Format SPARQL files in-place:

sparql format path/to/query.rq
sparql format path/to/directory/

Check if files are formatted without making changes:

sparql format --check path/to/query.rq

Usage

import sparqlkit

query = r'''
PREFIX : <http://www.example.org/>
SELECT * WHERE { ?s ?p ?o }
'''

# Use the convenience function
formatted = sparqlkit.format_string(query)
print(formatted)

Statement type detection

Determine the type and sub-type of a SPARQL statement:

import sparqlkit

# From a statement string
result = sparqlkit.statement_type_from_string("SELECT * WHERE { ?s ?p ?o }")
print(result.type)     # SparqlType.QUERY
print(result.subtype)  # QuerySubType.SELECT

# From a parsed tree
tree = sparqlkit.parse("INSERT DATA { <s> <p> <o> }")
result = sparqlkit.statement_type(tree)
print(result.type)     # SparqlType.UPDATE
print(result.subtype)  # UpdateSubType.INSERT_DATA

Supported query sub-types: SELECT, CONSTRUCT, DESCRIBE, ASK

Supported update sub-types: INSERT_WHERE, INSERT_DATA, DELETE_WHERE, DELETE_DATA, MODIFY, DROP, CLEAR, LOAD, CREATE, ADD, MOVE, COPY

Note: MODIFY includes both INSERT and DELETE operations. E.g., DELETE {…} INSERT {…} WHERE {…}

Preserving comments

Comments are preserved end-to-end through format_string and parse/serialize by default. To disable comment preservation, use preserve_comments=False:

import sparqlkit

query = "SELECT * WHERE { # comment\n  ?s ?p ?o }\n"
formatted = sparqlkit.format_string(query)
print(formatted)

tree = sparqlkit.parse(query)
print(sparqlkit.serialize(tree))

no_comments = sparqlkit.format_string(query, preserve_comments=False)
print(no_comments)

Notes:

  • Comments are preserved using stable anchoring (nearby-token association), not exact original spacing.
  • Comments are emitted as standalone lines by default for safety, but common inline forms are preserved:
    • SELECT ?x # comment (inline after a token)
    • WHERE { # comment (inline after {)
    • FILTER(... ) # comment (inline after ))

For advanced usage with the AST:

from sparqlkit.parser import sparql_query_parser
from sparqlkit.serializer import SparqlSerializer

tree = sparql_query_parser.parse(query)
serializer = SparqlSerializer()
result = serializer.visit_topdown(tree)
print(result)

Features

Iterative Stack-Based Serializer

The SPARQL serializer uses an iterative stack-based approach, allowing serialization of queries with arbitrary complexity and nesting depth (e.g., 1500+ nested OPTIONALs) without triggering Python's RecursionError.

Deep Nesting Example

from sparqlkit.parser import sparql_query_parser
from sparqlkit.serializer import SparqlSerializer

# Create a deeply nested query string
depth = 2000
query = "SELECT * WHERE { " + ("OPTIONAL { " * depth) + "?s ?p ?o" + (" }" * depth) + " }"

# Parse and serialize (no RecursionError)
tree = sparql_query_parser.parse(query)
serializer = SparqlSerializer()
result = serializer.visit_topdown(tree)
print(f"Successfully serialized query with nesting depth {depth}")

Extensibility

The serializer can be extended through subclassing to customize output:

from sparqlkit.serializer import SparqlSerializer
from lark import Tree

class CustomSerializer(SparqlSerializer):
    def _build_handler_map(self):
        handlers = super()._build_handler_map()
        handlers["var"] = {"enter": CustomSerializer._custom_var_enter, "exit": None}
        return handlers

    def _custom_var_enter(self, tree: Tree, context: dict) -> bool:
        self._parts.append(tree.children[0].value.upper())
        self._parts.append(" ")
        return True

Conformance

The parser and serializer passes all 1,070+ tests including those from the https://github.com/w3c/rdf-tests repository.

Metadata

Release files for sparqlkit 0.4.1

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

Source distribution (sdist)

Source distribution for sparqlkit 0.4.1
File Size Uploaded
sparqlkit-0.4.1.tar.gz 142.9 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for sparqlkit 0.4.1
File Interpreter ABI Platform
sparqlkit-0.4.1-py3-none-any.whl Python 3 none any Details

Total release size: 175.4 kB

Release files / sparqlkit-0.4.1.tar.gz

Download URL sparqlkit-0.4.1.tar.gz
Size 142.9 kB
Tags Source
SHA-256 checksum
How to use checksums
0018e4c200348c6a4f28a60ad8bb6fdc18db985b7f762cf4280904c18ba210be
BLAKE2b-256 checksum
How to use checksums
bb8f48475950a74a6188affc3449d7b3d3a554a53838280f702349cd4e803618
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.7

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Jan 26, 2026.

Transparency log

Release files / sparqlkit-0.4.1-py3-none-any.whl

Download URL sparqlkit-0.4.1-py3-none-any.whl
Size 32.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
680820029dbe39edf0f099b01580e78819d6cbabf09a7fc2ac81e88b2af6ae62
BLAKE2b-256 checksum
How to use checksums
53964bc511a564db0797ddb7fb06b80d8e0c9d9f5bc4daaca0c56fb377064d2a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.7

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Jan 26, 2026.

Transparency log

Release history Release notifications | RSS feed

This release

0.4.1 This release

2 release files

0.4.0

2 release files

0.3.0

2 release files

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