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)
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.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file sparqlkit-0.4.0.tar.gz.
File metadata
- Download URL: sparqlkit-0.4.0.tar.gz
- Upload date:
- Size: 142.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
2c8562a8f2d5b2375779cef74f187b8b61093a454110f932cedf507fb13d5443
|
|
| MD5 |
36a01b4fb90e62807f880c71af10938e
|
|
| BLAKE2b-256 |
d9993bbf2bd2cf7187985970d00715512a3b2b8d2eb9a0be7ecc41e5dfbf2bb4
|
Provenance
The following attestation bundles were made for sparqlkit-0.4.0.tar.gz:
Publisher:
pypi.yml on Kurrawong/sparqlkit
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
sparqlkit-0.4.0.tar.gz -
Subject digest:
2c8562a8f2d5b2375779cef74f187b8b61093a454110f932cedf507fb13d5443 - Sigstore transparency entry: 854982557
- Sigstore integration time:
-
Permalink:
Kurrawong/sparqlkit@d3b9f6518a2b2bb6e779f0a41ed09fb3056df1fe -
Branch / Tag:
refs/tags/0.4.0 - Owner: https://github.com/Kurrawong
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
pypi.yml@d3b9f6518a2b2bb6e779f0a41ed09fb3056df1fe -
Trigger Event:
release
-
Statement type:
File details
Details for the file sparqlkit-0.4.0-py3-none-any.whl.
File metadata
- Download URL: sparqlkit-0.4.0-py3-none-any.whl
- Upload date:
- Size: 32.4 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
564d6e4a3b62596a666f8eb5e9a5ee6a91517c942fd6c363c48b6cf0bebfb2c0
|
|
| MD5 |
3bf73b707b6c8b3d6c515fba07d42a3c
|
|
| BLAKE2b-256 |
999960b1c14223a72db858114ddc47ac80a721c81b5dddddef64a122186bb333
|
Provenance
The following attestation bundles were made for sparqlkit-0.4.0-py3-none-any.whl:
Publisher:
pypi.yml on Kurrawong/sparqlkit
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
sparqlkit-0.4.0-py3-none-any.whl -
Subject digest:
564d6e4a3b62596a666f8eb5e9a5ee6a91517c942fd6c363c48b6cf0bebfb2c0 - Sigstore transparency entry: 854982559
- Sigstore integration time:
-
Permalink:
Kurrawong/sparqlkit@d3b9f6518a2b2bb6e779f0a41ed09fb3056df1fe -
Branch / Tag:
refs/tags/0.4.0 - Owner: https://github.com/Kurrawong
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
pypi.yml@d3b9f6518a2b2bb6e779f0a41ed09fb3056df1fe -
Trigger Event:
release
-
Statement type: