Namespacecraft is a tiny toolkit for composing URI namespaces.
>>> from namespacecraft import Namespace
>>> EX = Namespace('http://example.org/')
>>> EX.a
Term('http://example.org/a')
>>> Namespace('http://example.org').terminates_with('#') / 'a' / 'b' / 'c' + 'x'
Term('http://example.org/a/b/c#x')Build paths using the / operator.
>>> Namespace('http://example.org/') / 'a' / 'b' / 'c'
Namespace('http://example.org/a/b/c')You can pass a list or tuple to / to append multiple path components at once.
>>> Namespace('http://example.org') / [1, 2, 3]
Namespace('http://example.org/1/2/3')Use terminates_with() to set the final delimiter.
>>> Namespace('http://example.org').terminates_with('#') / 'a' / 'b'
Namespace('http://example.org/a/b#')Create terms by accessing a Namespace attribute.
>>> EX = Namespace('http://example.org/')
>>> EX.a
Term('http://example.org/a')Or by getting an attribute by name.
>>> EX['b']
Term('http://example.org/b')Or with the + operator.
>>> EX + 1
Term('http://example.org/1')Namespace will create terms in any class that initialises from str. For example create terms as instances of rdflib.URIRef.
from namespacecraft import Namespace
from rdflib import Graph, URIRef
EX = Namespace('http://example.org/', term_cls=URIRef).terminates_with('/') / 'a/b/c'
graph = Graph()
graph.add((EX.s, EX.p, EX.o))
print(graph.serialize(format='turtle'))@prefix ns1: <http://example.org/a/b/c/> .
ns1:s ns1:p ns1:o .pip install namespacecraft-
The
+operator returns aTermobject. Any further+operations are just string concatenations.>>> Namespace('http://example.org/') + 'a' Term('http://example.org/a') >>> Namespace('http://example.org/') + 'a' + 'b' Term('http://example.org/ab')
-
Namespaces ending with
#are always terminal. Any path added via/immediately returns aTerm, and further/operations are not allowed.>>> BASE = Namespace('http://example.org#') >>> BASE / 'section' Term('http://example.org#section') >>> (BASE / 'section') / 'subsection' TypeError: unsupported operand type(s) for /: 'Term' and 'str'
-
You cannot set a trailing delimiter on a hash namespace. Attempting to do so will raise a
ValueError.>>> BASE = Namespace('http://example.org#') >>> BASE.terminates_with('/') ValueError: Cannot set a trailing delimiter on a hash namespace
pytest