Get SPARQL syntax string from rdflib.path.Path · Issue #421 · RDFLib/rdflib (original) (raw)
The SPARQL property paths in rdflib.paths
are great for slicing, etc.
However, there is no straightforward way to get back actual, usable SPARQL syntax for more complex query patterns, even though the user would have to understand said syntax to make sense of what comes out of __repr__
, or create it with the handy typographic shortcuts!
What I would like is:
from rdflib.namespaces import FOAF, RDFS path = ~FOAF.knows/RDFS.label
some magic
"~http://xmlns.com/foaf/0.1/knows/http://www.w3.org/2000/01/rdf-schema#label"
The __repr__
methods almost do this:
print path "Path(Path(~http://xmlns.com/foaf/0.1/knows) / http://www.w3.org/2000/01/rdf-schema#label)"
Perhaps implementing __str__
, in addition to __repr__
, and having each call str
and repr
repectively, would work:
class InvPath(Path): ...
def __repr__(self):
return "InvPath(%s)" % (repr(self.arg),)
def __str__(self):
return "~%s" % (str(self.arg),)
In the meantime, I am using this: just making this available could be helpful.
from rdflib import paths, term
def path2sparql(path): if isinstance(path, paths.InvPath): return "~%s" % path2sparql(path.arg) elif isinstance(path, paths.SequencePath): return "/".join(path2sparql(x) for x in path.args) elif isinstance(path, term.URIRef): return "<%s>" % path elif isinstance(path, paths.AlternativePath): return "|".join(path2sparql(x) for x in path.args) elif isinstance(path, paths.MulPath): return "%s%s" % (path2sparql(path.path), path.mod) raise NotImplemented("Unhandled type for property path %s", path)