rdflib.namespace package

Module contents

Namespace Utilities

RDFLib provides mechanisms for managing Namespaces.

In particular, there is a Namespace class that takes as its argument the base URI of the namespace.

>>> from rdflib.namespace import Namespace
>>> RDFS = Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#")

Fully qualified URIs in the namespace can be constructed either by attribute or by dictionary access on Namespace instances:

>>> RDFS.seeAlso
rdflib.term.URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#seeAlso')
>>> RDFS['seeAlso']
rdflib.term.URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#seeAlso')

Automatic handling of unknown predicates

As a programming convenience, a namespace binding is automatically created when rdflib.term.URIRef predicates are added to the graph.

Importable namespaces

The following namespaces are available by directly importing from rdflib:

  • BRICK

  • CSVW

  • DC

  • DCAT

  • DCMITYPE

  • DCTERMS

  • DCAM

  • DOAP

  • FOAF

  • ODRL2

  • ORG

  • OWL

  • PROF

  • PROV

  • QB

  • RDF

  • RDFS

  • SDO

  • SH

  • SKOS

  • SOSA

  • SSN

  • TIME

  • VANN

  • VOID

  • WGS

  • XSD

>>> from rdflib.namespace import RDFS
>>> RDFS.seeAlso
rdflib.term.URIRef('http://www.w3.org/2000/01/rdf-schema#seeAlso')
class rdflib.namespace.ClosedNamespace(uri: str, terms: List[str])[source]

Bases: Namespace

A namespace with a closed list of members

Trying to create terms not listed is an error

__annotations__ = {'_ClosedNamespace__uris': 'Dict[str, URIRef]'}
__contains__(ref)[source]

Allows to check if a URI is within (starts with) this Namespace.

>>> from rdflib import URIRef
>>> namespace = Namespace('http://example.org/')
>>> uri = URIRef('http://example.org/foo')
>>> uri in namespace
True
>>> person_class = namespace['Person']
>>> person_class in namespace
True
>>> obj = URIRef('http://not.example.org/bar')
>>> obj in namespace
False
Parameters:

ref (str)

Return type:

bool

__dir__()[source]

Default dir() implementation.

Return type:

List[str]

__firstlineno__ = 335
__getattr__(name)[source]
Parameters:

name (str)

Return type:

URIRef

__getitem__(key)[source]

Return self[key].

Parameters:

key (str)

Return type:

URIRef

__module__ = 'rdflib.namespace'
static __new__(cls, uri, terms)[source]
Parameters:
  • uri (str)

  • terms (List[str])

__repr__()[source]

Return repr(self).

Return type:

str

__static_attributes__ = ()
term(name)[source]
Parameters:

name (str)

Return type:

URIRef

property uri: str
class rdflib.namespace.Namespace(value: str | bytes)[source]

Bases: str

Utility class for quickly generating URIRefs with a common prefix

>>> from rdflib.namespace import Namespace
>>> n = Namespace("http://example.org/")
>>> n.Person # as attribute
rdflib.term.URIRef('http://example.org/Person')
>>> n['first-name'] # as item - for things that are not valid python identifiers
rdflib.term.URIRef('http://example.org/first-name')
>>> n.Person in n
True
>>> n2 = Namespace("http://example2.org/")
>>> n.Person in n2
False
__annotations__ = {}
__contains__(ref)[source]

Allows to check if a URI is within (starts with) this Namespace.

>>> from rdflib import URIRef
>>> namespace = Namespace('http://example.org/')
>>> uri = URIRef('http://example.org/foo')
>>> uri in namespace
True
>>> person_class = namespace['Person']
>>> person_class in namespace
True
>>> obj = URIRef('http://not.example.org/bar')
>>> obj in namespace
False
Parameters:

ref (str)

Return type:

bool

__dict__ = mappingproxy({'__module__': 'rdflib.namespace', '__firstlineno__': 130, '__doc__': '\nUtility class for quickly generating URIRefs with a common prefix\n\n>>> from rdflib.namespace import Namespace\n>>> n = Namespace("http://example.org/")\n>>> n.Person # as attribute\nrdflib.term.URIRef(\'http://example.org/Person\')\n>>> n[\'first-name\'] # as item - for things that are not valid python identifiers\nrdflib.term.URIRef(\'http://example.org/first-name\')\n>>> n.Person in n\nTrue\n>>> n2 = Namespace("http://example2.org/")\n>>> n.Person in n2\nFalse\n', '__new__': <staticmethod(<function Namespace.__new__>)>, 'title': <property object>, 'term': <function Namespace.term>, '__getitem__': <function Namespace.__getitem__>, '__getattr__': <function Namespace.__getattr__>, '__repr__': <function Namespace.__repr__>, '__contains__': <function Namespace.__contains__>, '__static_attributes__': (), '__dict__': <attribute '__dict__' of 'Namespace' objects>, '__weakref__': <attribute '__weakref__' of 'Namespace' objects>, '__annotations__': {}})
__firstlineno__ = 130
__getattr__(name)[source]
Parameters:

name (str)

Return type:

URIRef

__getitem__(key)[source]

Return self[key].

Parameters:

key (str)

Return type:

URIRef

__module__ = 'rdflib.namespace'
static __new__(cls, value)[source]
Parameters:

value (Union[str, bytes])

Return type:

Namespace

__repr__()[source]

Return repr(self).

Return type:

str

__static_attributes__ = ()
__weakref__

list of weak references to the object

term(name)[source]
Parameters:

name (str)

Return type:

URIRef

property title: URIRef

Return a version of the string where each word is titlecased.

More specifically, words start with uppercased characters and all remaining cased characters have lower case.

class rdflib.namespace.NamespaceManager(graph, bind_namespaces='rdflib')[source]

Bases: object

Class for managing prefix => namespace mappings

This class requires an RDFlib Graph as an input parameter and may optionally have the parameter bind_namespaces set. This second parameter selects a strategy which is one of the following:

  • core:
    • binds several core RDF prefixes only

    • owl, rdf, rdfs, xsd, xml from the NAMESPACE_PREFIXES_CORE object

  • rdflib:
    • binds all the namespaces shipped with RDFLib as DefinedNamespace instances

    • all the core namespaces and all the following: brick, csvw, dc, dcat

    • dcmitype, dcterms, dcam, doap, foaf, geo, odrl, org, prof, prov, qb, schema

    • sh, skos, sosa, ssn, time, vann, void

    • see the NAMESPACE_PREFIXES_RDFLIB object for the up-to-date list

    • this is default

  • none:
    • binds no namespaces to prefixes

    • note this is NOT default behaviour

  • cc:
    • using prefix bindings from prefix.cc which is a online prefixes database

    • not implemented yet - this is aspirational

Attention

The namespaces bound for specific values of bind_namespaces constitute part of RDFLib’s public interface, so changes to them should only be additive within the same minor version. Removing values, or removing namespaces that are bound by default, constitutes a breaking change.

See the Sample usage

>>> import rdflib
>>> from rdflib import Graph
>>> from rdflib.namespace import Namespace, NamespaceManager
>>> EX = Namespace('http://example.com/')
>>> namespace_manager = NamespaceManager(Graph())
>>> namespace_manager.bind('ex', EX, override=False)
>>> g = Graph()
>>> g.namespace_manager = namespace_manager
>>> all_ns = [n for n in g.namespace_manager.namespaces()]
>>> assert ('ex', rdflib.term.URIRef('http://example.com/')) in all_ns
>>>
Parameters:
  • graph (Graph)

  • bind_namespaces (Literal['core', 'rdflib', 'none'])

__contains__(ref)[source]
Parameters:

ref (str)

Return type:

bool

__dict__ = mappingproxy({'__module__': 'rdflib.namespace', '__firstlineno__': 394, '__doc__': "Class for managing prefix => namespace mappings\n\nThis class requires an RDFlib Graph as an input parameter and may optionally have\nthe parameter bind_namespaces set. This second parameter selects a strategy which\nis one of the following:\n\n* core:\n    * binds several core RDF prefixes only\n    * owl, rdf, rdfs, xsd, xml from the NAMESPACE_PREFIXES_CORE object\n* rdflib:\n    * binds all the namespaces shipped with RDFLib as DefinedNamespace instances\n    * all the core namespaces and all the following: brick, csvw, dc, dcat\n    * dcmitype, dcterms, dcam, doap, foaf, geo, odrl, org, prof, prov, qb, schema\n    * sh, skos, sosa, ssn, time, vann, void\n    * see the NAMESPACE_PREFIXES_RDFLIB object for the up-to-date list\n    * this is default\n* none:\n    * binds no namespaces to prefixes\n    * note this is NOT default behaviour\n* cc:\n    * using prefix bindings from prefix.cc which is a online prefixes database\n    * not implemented yet - this is aspirational\n\n.. attention::\n\n    The namespaces bound for specific values of ``bind_namespaces``\n    constitute part of RDFLib's public interface, so changes to them should\n    only be additive within the same minor version. Removing values, or\n    removing namespaces that are bound by default, constitutes a breaking\n    change.\n\nSee the\nSample usage\n\n.. code-block:: pycon\n\n    >>> import rdflib\n    >>> from rdflib import Graph\n    >>> from rdflib.namespace import Namespace, NamespaceManager\n    >>> EX = Namespace('http://example.com/')\n    >>> namespace_manager = NamespaceManager(Graph())\n    >>> namespace_manager.bind('ex', EX, override=False)\n    >>> g = Graph()\n    >>> g.namespace_manager = namespace_manager\n    >>> all_ns = [n for n in g.namespace_manager.namespaces()]\n    >>> assert ('ex', rdflib.term.URIRef('http://example.com/')) in all_ns\n    >>>\n", '__init__': <function NamespaceManager.__init__>, '__contains__': <function NamespaceManager.__contains__>, 'reset': <function NamespaceManager.reset>, 'store': <property object>, 'qname': <function NamespaceManager.qname>, 'curie': <function NamespaceManager.curie>, 'qname_strict': <function NamespaceManager.qname_strict>, 'normalizeUri': <function NamespaceManager.normalizeUri>, 'compute_qname': <function NamespaceManager.compute_qname>, 'compute_qname_strict': <function NamespaceManager.compute_qname_strict>, 'expand_curie': <function NamespaceManager.expand_curie>, '_store_bind': <function NamespaceManager._store_bind>, 'bind': <function NamespaceManager.bind>, 'namespaces': <function NamespaceManager.namespaces>, 'absolutize': <function NamespaceManager.absolutize>, '__static_attributes__': ('__cache', '__cache_strict', '__log', '__strie', '__trie', 'graph'), '__dict__': <attribute '__dict__' of 'NamespaceManager' objects>, '__weakref__': <attribute '__weakref__' of 'NamespaceManager' objects>, '__annotations__': {'__cache': 'Dict[str, Tuple[str, URIRef, str]]', '__cache_strict': 'Dict[str, Tuple[str, URIRef, str]]', '__strie': 'Dict[str, Any]', '__trie': 'Dict[str, Any]'}})
__firstlineno__ = 394
__init__(graph, bind_namespaces='rdflib')[source]
Parameters:
  • graph (Graph)

  • bind_namespaces (Literal['core', 'rdflib', 'none'])

__module__ = 'rdflib.namespace'
__static_attributes__ = ('__cache', '__cache_strict', '__log', '__strie', '__trie', 'graph')
__weakref__

list of weak references to the object

absolutize(uri, defrag=1)[source]
Parameters:
  • uri (str)

  • defrag (int)

Return type:

URIRef

bind(prefix, namespace, override=True, replace=False)[source]

Bind a given namespace to the prefix

If override, rebind, even if the given namespace is already bound to another prefix.

If replace, replace any existing prefix with the new namespace

Parameters:
  • prefix (Optional[str])

  • namespace (Any)

  • override (bool)

  • replace (bool)

Return type:

None

compute_qname(uri, generate=True)[source]
Parameters:
  • uri (str)

  • generate (bool)

Return type:

Tuple[str, URIRef, str]

compute_qname_strict(uri, generate=True)[source]
Parameters:
  • uri (str)

  • generate (bool)

Return type:

Tuple[str, str, str]

curie(uri, generate=True)[source]

From a URI, generate a valid CURIE.

Result is guaranteed to contain a colon separating the prefix from the name, even if the prefix is an empty string.

Warning

When generate is True (which is the default) and there is no matching namespace for the URI in the namespace manager then a new namespace will be added with prefix ns{index}.

Thus, when generate is True, this function is not a pure function because of this side-effect.

This default behaviour is chosen so that this function operates similarly to NamespaceManager.qname.

Parameters:
  • uri (str) – URI to generate CURIE for.

  • generate (bool) – Whether to add a prefix for the namespace if one doesn’t already exist. Default: True.

Return type:

str

Returns:

CURIE for the URI.

Raises:

KeyError – If generate is False and the namespace doesn’t already have a prefix.

expand_curie(curie)[source]

Expand a CURIE of the form <prefix:element>, e.g. “rdf:type” into its full expression:

>>> import rdflib
>>> g = rdflib.Graph()
>>> g.namespace_manager.expand_curie("rdf:type")
rdflib.term.URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#type')

Raises exception if a namespace is not bound to the prefix.

Parameters:

curie (str)

Return type:

URIRef

namespaces()[source]
Return type:

Iterable[Tuple[str, URIRef]]

normalizeUri(rdfTerm)[source]

Takes an RDF Term and ‘normalizes’ it into a QName (using the registered prefix) or (unlike compute_qname) the Notation 3 form for URIs: <…URI…>

Parameters:

rdfTerm (str)

Return type:

str

qname(uri)[source]
Parameters:

uri (str)

Return type:

str

qname_strict(uri)[source]
Parameters:

uri (str)

Return type:

str

reset()[source]
Return type:

None

property store: Store
rdflib.namespace.is_ncname(name)[source]
Parameters:

name (str)

Return type:

int

rdflib.namespace.split_uri(uri, split_start=['Ll', 'Lu', 'Lo', 'Lt', 'Nl', 'Nd'])[source]
Parameters:
  • uri (str)

  • split_start (List[str])

Return type:

Tuple[str, str]