Search code examples
pythonsparqlattributeerrorrdflib

rdflib.plugins.sparql not found?


I am working through some basic rdflib stuff in python, trying to figure it out, and I am running into what seems like a basic problem.

The code is also here, the third example under Lecture 3: SPARQL.

import rdflib

g = rdflib.Graph()
g.parse("family.ttl", format='ttl')

q = rdflib.plugins.sparql.prepareQuery(
        """SELECT ?child ?sister WHERE {
                  ?child fam:hasParent ?parent .
                  ?parent fam:hasSister ?sister .
       }""",
       initNs = { "fam": "http://example.org/family#"})

sm = rdflib.URIRef("http://example.org/royal#SverreMagnus")

for row in g.query(q, initBindings={'child': sm}):
        print(row)

The family.ttl file is in the same directory and is as follows, as per the example.

@prefix rex: <http://example.org/royal#> .
@prefix fam: <http://example.org/family#> .

rex:IngridAlexandra fam:hasParent rex:HaakonMagnus .
rex:SverreMagnus fam:hasParent rex:HaakonMagnus .
rex:HaakonMagnus fam:hasParent rex:Harald .
rex:MarthaLouise fam:hasParent rex:Harald .
rex:HaakonMagnus fam:hasSister rex:MarthaLouise .

When I try to run this, I get an error.

AttributeError: module 'rdflib.plugins' has no attribute 'sparql'

Python is version 3.9.5, and rdflib is 6.0.1. Anyone know what the deal might be?


Solution

  • Just try changing your imports a bit, like this:

    import rdflib
    from rdflib.plugins import sparql
    
    g = rdflib.Graph()
    g.parse("family.ttl")
    
    q = sparql.prepareQuery(
        """SELECT ?child ?sister WHERE {
                  ?child fam:hasParent ?parent .
                  ?parent fam:hasSister ?sister .
       }""",
       initNs={"fam": "http://example.org/family#"})
    
    sm = rdflib.URIRef("http://example.org/royal#SverreMagnus")
    
    for row in g.query(q, initBindings={'child': sm}):
        print(row)