Namespaces and Bindings

RDFLib provides several short-cuts to working with many URIs in the same namespace.

The rdflib.namespace defines the rdflib.namespace.Namespace class which lets you easily create URIs in a namespace:

from rdflib import Namespace

n = Namespace("")
n.Person # as attribute
# = rdflib.term.URIRef(u'')

n['first%20name'] # as item - for things that are not valid python identifiers
# = rdflib.term.URIRef(u'')

The namespace module also defines many common namespaces such as RDF, RDFS, OWL, FOAF, SKOS, etc.

Namespaces can also be associated with prefixes, in a rdflib.namespace.NamespaceManager, i.e. using foaf for Each RDFLib graph has a namespace_manager that keeps a list of namespace to prefix mappings. The namespace manager is populated when reading in RDF, and these prefixes are used when serialising RDF, or when parsing SPARQL queries. Additional prefixes can be bound with the rdflib.graph.bind() method.

Namespaces in SPARQL Queries

The initNs argument supplied to query() is a dictionary of namespaces to be expanded in the query string. If you pass no initNs argument, the namespaces registered with the graphs namespace_manager are used:

from rdflib.namespace import FOAF
graph.query('SELECT * WHERE { ?p a foaf:Person }', initNs={ 'foaf': FOAF })

In order to use an empty prefix (e.g. ?a :knows ?b), use a PREFIX directive with no prefix in the SPARQL query to set a default namespace: