Skip to main content

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

Project description

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)

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.

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

sparqlkit-0.3.0.tar.gz (140.3 kB view details)

Uploaded Source

Built Distribution

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

sparqlkit-0.3.0-py3-none-any.whl (30.7 kB view details)

Uploaded Python 3

File details

Details for the file sparqlkit-0.3.0.tar.gz.

File metadata

  • Download URL: sparqlkit-0.3.0.tar.gz
  • Upload date:
  • Size: 140.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for sparqlkit-0.3.0.tar.gz
Algorithm Hash digest
SHA256 a2fb8d7563f592c261c99a79b5c9c4d9de020c6a1136096d0dfd38b0803e9a46
MD5 4e017428ce61379f0916d537804e04ca
BLAKE2b-256 b0890386e447e6b537ec55a260f82c1b76407b84a5d46f274be939390b82c43b

See more details on using hashes here.

Provenance

The following attestation bundles were made for sparqlkit-0.3.0.tar.gz:

Publisher: pypi.yml on Kurrawong/sparqlkit

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file sparqlkit-0.3.0-py3-none-any.whl.

File metadata

  • Download URL: sparqlkit-0.3.0-py3-none-any.whl
  • Upload date:
  • Size: 30.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for sparqlkit-0.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 19f6b8b89f740ecc5f57a05460c2b161d0e43dbdd24721b5699cc389dc560e06
MD5 3da8f236cc7bfa1b98688988c39daffe
BLAKE2b-256 4181ac5ebe156b1741254241637e83c14897c8638c9219ddd75012f526fbb1ea

See more details on using hashes here.

Provenance

The following attestation bundles were made for sparqlkit-0.3.0-py3-none-any.whl:

Publisher: pypi.yml on Kurrawong/sparqlkit

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

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