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.


Each graph comes with a NamespaceManager instance in the namespace_manager field; you can use the bind method of this instance to bind a prefix to a namespace URI:

myGraph.namespace_manager.bind('prefix', URIRef('scheme:my-namespace-uri:'))
myGraph.namespace_manager.bind('owl', OWL_NS, override=False)

It has a method to normalize a given url :


For simple output, or simple serialisation, you often want a nice readable representation of a term. All terms have a .n3(namespace_manager = None) method, which will return a suitable N3 format:

>>> from rdflib import Graph, URIRef, Literal, BNode
>>> from rdflib.namespace import FOAF, NamespaceManager

>>> person = URIRef('')
>>> person.n3()

>>> g = Graph()
>>> g.bind("foaf", FOAF)

>>> person.n3(g.namespace_manager)

>>> l = Literal(2)
>>> l.n3()

>>> l.n3(g.namespace_manager)

The namespace manage also has a useful method compute_qname g.namespace_manager.compute_qname(x) which takes an url and decomposes it into the parts:

(“ns2”, URIRef(“http://foo/bar#”), “baz”))

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: