src/rdflib/namespace/__init__.py
1"""
2# Namespace Utilities
3
4RDFLib provides mechanisms for managing Namespaces.
5
6In particular, there is a [`Namespace`][rdflib.namespace.Namespace] class
7that takes as its argument the base URI of the namespace.
8
9```python
10>>> from rdflib.namespace import Namespace
11>>> RDFS = Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#")
12
13```
14
15Fully qualified URIs in the namespace can be constructed either by attribute
16or by dictionary access on Namespace instances:
17
18```python
19>>> RDFS.seeAlso
20rdflib.term.URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#seeAlso')
21>>> RDFS['seeAlso']
22rdflib.term.URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#seeAlso')
23
24```
25
26## Automatic handling of unknown predicates
27
28As a programming convenience, a namespace binding is automatically
29created when [`URIRef`][rdflib.term.URIRef] predicates are added to the graph.
30
31## Importable namespaces
32
33The following namespaces are available by directly importing from rdflib:
34
35* BRICK
36* CSVW
37* DC
38* DCAT
39* DCMITYPE
40* DCTERMS
41* DCAM
42* DOAP
43* FOAF
44* ODRL2
45* ORG
46* OWL
47* PROF
48* PROV
49* QB
50* RDF
51* RDFS
52* SDO
53* SH
54* SKOS
55* SOSA
56* SSN
57* TIME
58* VANN
59* VOID
60* WGS
61* XSD
62
63```python
64>>> from rdflib.namespace import RDFS
65>>> RDFS.seeAlso
66rdflib.term.URIRef('http://www.w3.org/2000/01/rdf-schema#seeAlso')
67
68```
69"""
70
71from __future__ import annotations
72
73import logging
74import warnings
75
76try:
77 # Python >= 3.14
78 from annotationlib import (
79 get_annotations, # type: ignore[attr-defined,unused-ignore]
80 )
81except ImportError: # pragma: no cover
82 try:
83 # Python >= 3.10
84 from inspect import get_annotations # type: ignore[attr-defined,unused-ignore]
85 except ImportError:
86
87 def get_annotations(thing: Any) -> dict:
88 return thing.__annotations__
89
90
91from functools import lru_cache
92from pathlib import Path
93from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Set, Tuple, Union
94from unicodedata import category
95from urllib.parse import urldefrag, urljoin
96
97from rdflib.term import URIRef, Variable, _is_valid_uri
98
99if TYPE_CHECKING:
100 from rdflib.graph import Graph
101 from rdflib.store import Store
102
103
104__all__ = [
105 "is_ncname",
106 "split_uri",
107 "Namespace",
108 "ClosedNamespace",
109 "DefinedNamespace",
110 "NamespaceManager",
111 "BRICK",
112 "CSVW",
113 "DC",
114 "DCAM",
115 "DCAT",
116 "DCMITYPE",
117 "DCTERMS",
118 "DOAP",
119 "FOAF",
120 "GEO",
121 "ODRL2",
122 "ORG",
123 "OWL",
124 "PROF",
125 "PROV",
126 "QB",
127 "RDF",
128 "RDFS",
129 "SDO",
130 "SH",
131 "SKOS",
132 "SOSA",
133 "SSN",
134 "TIME",
135 "VANN",
136 "VOID",
137 "WGS",
138 "XSD",
139]
140
141logger = logging.getLogger(__name__)
142
143
144class Namespace(str):
145 """Utility class for quickly generating URIRefs with a common prefix.
146
147 ```python
148 >>> from rdflib.namespace import Namespace
149 >>> n = Namespace("http://example.org/")
150 >>> n.Person # as attribute
151 rdflib.term.URIRef('http://example.org/Person')
152 >>> n['first-name'] # as item - for things that are not valid python identifiers
153 rdflib.term.URIRef('http://example.org/first-name')
154 >>> n.Person in n
155 True
156 >>> n2 = Namespace("http://example2.org/")
157 >>> n.Person in n2
158 False
159
160 ```
161 """
162
163 def __new__(cls, value: Union[str, bytes]) -> Namespace:
164 try:
165 rt = str.__new__(cls, value)
166 except UnicodeDecodeError:
167 rt = str.__new__(cls, value, "utf-8") # type: ignore[arg-type]
168 return rt
169
170 # type error: Signature of "title" incompatible with supertype "str"
171 @property
172 def title(self) -> URIRef: # type: ignore[override]
173 # Override for DCTERMS.title to return a URIRef instead of str.title method
174 return URIRef(self + "title")
175
176 def term(self, name: str) -> URIRef:
177 # need to handle slices explicitly because of __getitem__ override
178 return URIRef(self + (name if isinstance(name, str) else ""))
179
180 def __getitem__(self, key: str) -> URIRef: # type: ignore[override]
181 return self.term(key)
182
183 def __getattr__(self, name: str) -> URIRef:
184 if name.startswith("__"): # ignore any special Python names!
185 raise AttributeError
186 return self.term(name)
187
188 def __repr__(self) -> str:
189 return f"Namespace({super().__repr__()})"
190
191 def __contains__(self, ref: str) -> bool: # type: ignore[override]
192 """Allows to check if a URI is within (starts with) this Namespace.
193
194 ```python
195 >>> from rdflib import URIRef
196 >>> namespace = Namespace('http://example.org/')
197 >>> uri = URIRef('http://example.org/foo')
198 >>> uri in namespace
199 True
200 >>> person_class = namespace['Person']
201 >>> person_class in namespace
202 True
203 >>> obj = URIRef('http://not.example.org/bar')
204 >>> obj in namespace
205 False
206
207 ```
208 """
209 return ref.startswith(self) # test namespace membership with "ref in ns" syntax
210
211
212class URIPattern(str):
213 """Utility class for creating URIs according to some pattern.
214
215 This supports either new style formatting with .format
216 or old-style with % operator.
217
218 ```python
219 >>> u=URIPattern("http://example.org/%s/%d/resource")
220 >>> u%('books', 12345)
221 rdflib.term.URIRef('http://example.org/books/12345/resource')
222
223 ```
224 """
225
226 def __new__(cls, value: Union[str, bytes]) -> URIPattern:
227 try:
228 rt = str.__new__(cls, value)
229 except UnicodeDecodeError:
230 if TYPE_CHECKING:
231 assert isinstance(value, bytes)
232 rt = str.__new__(cls, value, "utf-8")
233 return rt
234
235 def __mod__(self, *args, **kwargs) -> URIRef:
236 return URIRef(super().__mod__(*args, **kwargs))
237
238 def format(self, *args, **kwargs) -> URIRef:
239 return URIRef(super().format(*args, **kwargs))
240
241 def __repr__(self) -> str:
242 return f"URIPattern({super().__repr__()})"
243
244
245# _DFNS_RESERVED_ATTRS are attributes for which DefinedNamespaceMeta should
246# always raise AttributeError if they are not defined and which should not be
247# considered part of __dir__ results. These should be all annotations on
248# `DefinedNamespaceMeta`.
249_DFNS_RESERVED_ATTRS: Set[str] = {
250 "__slots__",
251 "_NS",
252 "_warn",
253 "_fail",
254 "_extras",
255 "_underscore_num",
256}
257
258# Some libraries probe classes for certain attributes or items.
259# This is a list of those attributes and items that should be ignored.
260_IGNORED_ATTR_LOOKUP: Set[str] = {
261 "_pytestfixturefunction", # pytest tries to look this up on Defined namespaces
262 "_partialmethod", # sphinx tries to look this up during autodoc generation
263}
264
265
266class DefinedNamespaceMeta(type):
267 """Utility metaclass for generating URIRefs with a common prefix."""
268
269 __slots__: Tuple[str, ...] = tuple()
270
271 _NS: Namespace
272 _warn: bool = True
273 _fail: bool = False # True means mimic ClosedNamespace
274 _extras: List[str] = [] # List of non-pythonesque items
275 _underscore_num: bool = False # True means pass "_n" constructs
276
277 @lru_cache(maxsize=None)
278 def __getitem__(cls, name: str, default=None) -> URIRef:
279 name = str(name)
280
281 if name in _DFNS_RESERVED_ATTRS:
282 raise KeyError(
283 f"DefinedNamespace like object has no access item named {name!r}"
284 )
285 elif name in _IGNORED_ATTR_LOOKUP:
286 raise KeyError()
287 if (cls._warn or cls._fail) and name not in cls:
288 if cls._fail:
289 raise AttributeError(f"term '{name}' not in namespace '{cls._NS}'")
290 else:
291 warnings.warn(
292 f"Code: {name} is not defined in namespace {cls.__name__}",
293 stacklevel=3,
294 )
295 return cls._NS[name]
296
297 def __getattr__(cls, name: str):
298 if name in _IGNORED_ATTR_LOOKUP:
299 raise AttributeError()
300 elif name in _DFNS_RESERVED_ATTRS:
301 raise AttributeError(
302 f"DefinedNamespace like object has no attribute {name!r}"
303 )
304 elif name.startswith("__"):
305 return super(DefinedNamespaceMeta, cls).__getattribute__(name)
306 return cls.__getitem__(name)
307
308 def __repr__(cls) -> str:
309 try:
310 ns_repr = repr(cls._NS)
311 except AttributeError:
312 ns_repr = "<DefinedNamespace>"
313 return f"Namespace({ns_repr})"
314
315 def __str__(cls) -> str:
316 try:
317 return str(cls._NS)
318 except AttributeError:
319 return "<DefinedNamespace>"
320
321 def __add__(cls, other: str) -> URIRef:
322 return cls.__getitem__(other)
323
324 def __contains__(cls, item: str) -> bool:
325 """Determine whether a URI or an individual item belongs to this namespace"""
326 try:
327 this_ns = cls._NS
328 except AttributeError:
329 return False
330 item_str = str(item)
331 if item_str.startswith(str(this_ns)):
332 item_str = item_str[len(str(this_ns)) :]
333 return any(
334 item_str in get_annotations(c)
335 or item_str in c._extras
336 or (cls._underscore_num and item_str[0] == "_" and item_str[1:].isdigit())
337 for c in cls.mro()
338 if issubclass(c, DefinedNamespace)
339 )
340
341 def __dir__(cls) -> Iterable[str]:
342 attrs = {str(x) for x in get_annotations(cls)}
343 # Removing these as they should not be considered part of the namespace.
344 attrs.difference_update(_DFNS_RESERVED_ATTRS)
345 values = {cls[str(x)] for x in attrs}
346 return values
347
348 def as_jsonld_context(self, pfx: str) -> dict: # noqa: N804
349 """Returns this DefinedNamespace as a JSON-LD 'context' object"""
350 terms = {pfx: str(self._NS)}
351 for key, term in get_annotations(self).items():
352 if issubclass(term, URIRef):
353 terms[key] = f"{pfx}:{key}"
354
355 return {"@context": terms}
356
357
358class DefinedNamespace(metaclass=DefinedNamespaceMeta):
359 """A Namespace with an enumerated list of members.
360
361 Warnings are emitted if unknown members are referenced if _warn is True.
362 """
363
364 __slots__: Tuple[str, ...] = tuple()
365
366 def __init__(self):
367 raise TypeError("namespace may not be instantiated")
368
369
370class ClosedNamespace(Namespace):
371 """
372 A namespace with a closed list of members
373
374 Trying to create terms not listed is an error
375 """
376
377 __uris: Dict[str, URIRef]
378
379 def __new__(cls, uri: str, terms: List[str]):
380 rt = super().__new__(cls, uri)
381 rt.__uris = {t: URIRef(rt + t) for t in terms} # type: ignore[attr-defined]
382 return rt
383
384 @property
385 def uri(self) -> str: # Back-compat
386 return str(self)
387
388 def term(self, name: str) -> URIRef:
389 uri = self.__uris.get(name)
390 if uri is None:
391 raise KeyError(f"term '{name}' not in namespace '{self}'")
392 return uri
393
394 def __getitem__(self, key: str) -> URIRef: # type: ignore[override]
395 return self.term(key)
396
397 def __getattr__(self, name: str) -> URIRef:
398 if name.startswith("__"): # ignore any special Python names!
399 raise AttributeError
400 else:
401 try:
402 return self.term(name)
403 except KeyError as e:
404 raise AttributeError(e)
405
406 def __repr__(self) -> str:
407 return f"{self.__module__}.{self.__class__.__name__}({str(self)!r})"
408
409 def __dir__(self) -> List[str]:
410 return list(self.__uris)
411
412 def __contains__(self, ref: str) -> bool: # type: ignore[override]
413 return (
414 ref in self.__uris.values()
415 ) # test namespace membership with "ref in ns" syntax
416
417 def _ipython_key_completions_(self) -> List[str]:
418 return dir(self)
419
420
421XMLNS = Namespace("http://www.w3.org/XML/1998/namespace")
422
423if TYPE_CHECKING:
424 from rdflib._type_checking import _NamespaceSetString
425
426_with_bind_override_fix = True
427
428
429class NamespaceManager:
430 """Class for managing prefix => namespace mappings
431
432 This class requires an RDFlib Graph as an input parameter and may optionally have
433 the parameter bind_namespaces set. This second parameter selects a strategy which
434 is one of the following:
435
436 * core:
437 * binds several core RDF prefixes only
438 * owl, rdf, rdfs, xsd, xml from the NAMESPACE_PREFIXES_CORE object
439 * rdflib:
440 * binds all the namespaces shipped with RDFLib as DefinedNamespace instances
441 * all the core namespaces and all the following: brick, csvw, dc, dcat
442 * dcmitype, dcterms, dcam, doap, foaf, geo, odrl, org, prof, prov, qb, schema
443 * sh, skos, sosa, ssn, time, vann, void
444 * see the NAMESPACE_PREFIXES_RDFLIB object for the up-to-date list
445 * this is default
446 * none:
447 * binds no namespaces to prefixes
448 * note this is NOT default behaviour
449 * cc:
450 * using prefix bindings from prefix.cc which is a online prefixes database
451 * not implemented yet - this is aspirational
452
453 !!! warning "Breaking changes"
454
455 The namespaces bound for specific values of `bind_namespaces`
456 constitute part of RDFLib's public interface, so changes to them should
457 only be additive within the same minor version. Removing values, or
458 removing namespaces that are bound by default, constitutes a breaking
459 change.
460
461 See the sample usage
462
463 ```python
464 >>> import rdflib
465 >>> from rdflib import Graph
466 >>> from rdflib.namespace import Namespace, NamespaceManager
467 >>> EX = Namespace('http://example.com/')
468 >>> namespace_manager = NamespaceManager(Graph())
469 >>> namespace_manager.bind('ex', EX, override=False)
470 >>> g = Graph()
471 >>> g.namespace_manager = namespace_manager
472 >>> all_ns = [n for n in g.namespace_manager.namespaces()]
473 >>> assert ('ex', rdflib.term.URIRef('http://example.com/')) in all_ns
474
475 ```
476 """
477
478 def __init__(self, graph: Graph, bind_namespaces: _NamespaceSetString = "rdflib"):
479 self.graph = graph
480 self.__cache: Dict[str, Tuple[str, URIRef, str]] = {}
481 self.__cache_strict: Dict[str, Tuple[str, URIRef, str]] = {}
482 self.__log = None
483 self.__strie: Dict[str, Any] = {}
484 self.__trie: Dict[str, Any] = {}
485 # This type declaration is here becuase there is no common base class
486 # for all namespaces and without it the inferred type of ns is not
487 # compatible with all prefixes.
488 ns: Any
489 # bind Namespaces as per options.
490 # default is core
491 if bind_namespaces == "none":
492 # binds no namespaces to prefixes
493 # note this is NOT default
494 pass
495 elif bind_namespaces == "rdflib":
496 # bind all the Namespaces shipped with RDFLib
497 for prefix, ns in _NAMESPACE_PREFIXES_RDFLIB.items():
498 self.bind(prefix, ns)
499 # ... don't forget the core ones too
500 for prefix, ns in _NAMESPACE_PREFIXES_CORE.items():
501 self.bind(prefix, ns)
502 elif bind_namespaces == "cc":
503 # bind any prefix that can be found with lookups to prefix.cc
504 # first bind core and rdflib ones
505 # work out remainder - namespaces without prefixes
506 # only look those ones up
507 raise NotImplementedError("Haven't got to this option yet")
508 elif bind_namespaces == "core":
509 # bind a few core RDF namespaces - default
510 for prefix, ns in _NAMESPACE_PREFIXES_CORE.items():
511 self.bind(prefix, ns)
512 else:
513 raise ValueError(f"unsupported namespace set {bind_namespaces}")
514
515 def __contains__(self, ref: str) -> bool:
516 # checks if a reference is in any of the managed namespaces with syntax
517 # "ref in manager". Note that we don't use "ref in ns", as
518 # NamespaceManager.namespaces() returns Iterator[Tuple[str, URIRef]]
519 # rather than Iterator[Tuple[str, Namespace]]
520 return any(ref.startswith(ns) for prefix, ns in self.namespaces())
521
522 def reset(self) -> None:
523 self.__cache = {}
524 self.__strie = {}
525 self.__trie = {}
526 for p, n in self.namespaces(): # repopulate the trie
527 insert_trie(self.__trie, str(n))
528
529 @property
530 def store(self) -> Store:
531 return self.graph.store
532
533 def qname(self, uri: str) -> str:
534 prefix, namespace, name = self.compute_qname(uri)
535 if prefix == "":
536 return name
537 else:
538 return ":".join((prefix, name))
539
540 def curie(self, uri: str, generate: bool = True) -> str:
541 """
542 From a URI, generate a valid CURIE.
543
544 Result is guaranteed to contain a colon separating the prefix from the
545 name, even if the prefix is an empty string.
546
547 !!! warning "Side-effect"
548 When `generate` is `True` (which is the default) and there is no
549 matching namespace for the URI in the namespace manager then a new
550 namespace will be added with prefix `ns{index}`.
551
552 Thus, when `generate` is `True`, this function is not a pure
553 function because of this side-effect.
554
555 This default behaviour is chosen so that this function operates
556 similarly to `NamespaceManager.qname`.
557
558 Args:
559 uri: URI to generate CURIE for.
560 generate: Whether to add a prefix for the namespace if one doesn't
561 already exist. Default: `True`.
562
563 Returns:
564 CURIE for the URI
565
566 Raises:
567 KeyError: If generate is `False` and the namespace doesn't already have
568 a prefix.
569 """
570 prefix, namespace, name = self.compute_qname(uri, generate=generate)
571 return ":".join((prefix, name))
572
573 def qname_strict(self, uri: str) -> str:
574 prefix, namespace, name = self.compute_qname_strict(uri)
575 if prefix == "":
576 return name
577 else:
578 return ":".join((prefix, name))
579
580 def normalizeUri(self, rdfTerm: str) -> str: # noqa: N802, N803
581 """
582 Takes an RDF Term and 'normalizes' it into a QName (using the
583 registered prefix) or (unlike compute_qname) the Notation 3
584 form for URIs: <...URI...>
585 """
586 try:
587 namespace, name = split_uri(rdfTerm)
588 if namespace not in self.__strie:
589 insert_strie(self.__strie, self.__trie, str(namespace))
590 namespace = URIRef(str(namespace))
591 except Exception:
592 if isinstance(rdfTerm, Variable):
593 return "?%s" % rdfTerm
594 else:
595 return "<%s>" % rdfTerm
596 prefix = self.store.prefix(namespace)
597 if prefix is None and isinstance(rdfTerm, Variable):
598 return "?%s" % rdfTerm
599 elif prefix is None:
600 return "<%s>" % rdfTerm
601 else:
602 qNameParts = self.compute_qname(rdfTerm) # noqa: N806
603 return ":".join([qNameParts[0], qNameParts[-1]])
604
605 def compute_qname(self, uri: str, generate: bool = True) -> Tuple[str, URIRef, str]:
606 prefix: Optional[str]
607 if uri not in self.__cache:
608 if not _is_valid_uri(uri):
609 raise ValueError(
610 '"{}" does not look like a valid URI, cannot serialize this. Did you want to urlencode it?'.format(
611 uri
612 )
613 )
614
615 try:
616 namespace, name = split_uri(uri)
617 except ValueError as e:
618 namespace = URIRef(uri)
619 prefix = self.store.prefix(namespace)
620 name = "" # empty prefix case, safe since not prefix is error
621 if not prefix:
622 raise e
623 if namespace not in self.__strie:
624 insert_strie(self.__strie, self.__trie, namespace)
625
626 if self.__strie[namespace]:
627 pl_namespace = get_longest_namespace(self.__strie[namespace], uri)
628 if pl_namespace is not None:
629 namespace = pl_namespace
630 name = uri[len(namespace) :]
631
632 namespace = URIRef(namespace)
633 prefix = self.store.prefix(namespace) # warning multiple prefixes problem
634
635 if prefix is None:
636 if not generate:
637 raise KeyError(
638 "No known prefix for {} and generate=False".format(namespace)
639 )
640 num = 1
641 while 1:
642 prefix = "ns%s" % num
643 if not self.store.namespace(prefix):
644 break
645 num += 1
646 self.bind(prefix, namespace)
647 self.__cache[uri] = (prefix, namespace, name)
648 return self.__cache[uri]
649
650 def compute_qname_strict(
651 self, uri: str, generate: bool = True
652 ) -> Tuple[str, str, str]:
653 # code repeated to avoid branching on strict every time
654 # if output needs to be strict (e.g. for xml) then
655 # only the strict output should bear the overhead
656 namespace: str
657 prefix: Optional[str]
658 prefix, namespace, name = self.compute_qname(uri, generate)
659 if is_ncname(str(name)):
660 return prefix, namespace, name
661 else:
662 if uri not in self.__cache_strict:
663 try:
664 namespace, name = split_uri(uri, NAME_START_CATEGORIES)
665 except ValueError:
666 message = (
667 "This graph cannot be serialized to a strict format "
668 "because there is no valid way to shorten {}".format(uri)
669 )
670 raise ValueError(message)
671 # omitted for strict since NCNames cannot be empty
672 # namespace = URIRef(uri)
673 # prefix = self.store.prefix(namespace)
674 # if not prefix:
675 # raise e
676
677 if namespace not in self.__strie:
678 insert_strie(self.__strie, self.__trie, namespace)
679
680 # omitted for strict
681 # if self.__strie[namespace]:
682 # pl_namespace = get_longest_namespace(self.__strie[namespace], uri)
683 # if pl_namespace is not None:
684 # namespace = pl_namespace
685 # name = uri[len(namespace):]
686
687 namespace = URIRef(namespace)
688 prefix = self.store.prefix(
689 namespace
690 ) # warning multiple prefixes problem
691
692 if prefix is None:
693 if not generate:
694 raise KeyError(
695 "No known prefix for {} and generate=False".format(
696 namespace
697 )
698 )
699 num = 1
700 while 1:
701 prefix = "ns%s" % num
702 if not self.store.namespace(prefix):
703 break
704 num += 1
705 self.bind(prefix, namespace)
706 self.__cache_strict[uri] = (prefix, namespace, name)
707
708 return self.__cache_strict[uri]
709
710 def expand_curie(self, curie: str) -> URIRef:
711 """
712 Expand a CURIE of the form <prefix:element>, e.g. "rdf:type"
713 into its full expression:
714
715 >>> import rdflib
716 >>> g = rdflib.Graph()
717 >>> g.namespace_manager.expand_curie("rdf:type")
718 rdflib.term.URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#type')
719
720 Raises exception if a namespace is not bound to the prefix.
721
722 """
723 if not type(curie) is str: # noqa: E714
724 raise TypeError(f"Argument must be a string, not {type(curie).__name__}.")
725 parts = curie.split(":", 1)
726 if len(parts) != 2:
727 raise ValueError(
728 "Malformed curie argument, format should be e.g. “foaf:name”."
729 )
730 ns = self.store.namespace(parts[0])
731 if ns is not None:
732 return URIRef(f"{str(ns)}{parts[1]}")
733 else:
734 raise ValueError(
735 f"Prefix \"{curie.split(':')[0]}\" not bound to any namespace."
736 )
737
738 def _store_bind(self, prefix: str, namespace: URIRef, override: bool) -> None:
739 if not _with_bind_override_fix:
740 return self.store.bind(prefix, namespace)
741 try:
742 return self.store.bind(prefix, namespace, override=override)
743 except TypeError as error:
744 if "override" in str(error):
745 logger.debug(
746 "caught a TypeError, "
747 "retrying call to %s.bind without override, "
748 "see https://github.com/RDFLib/rdflib/issues/1880 for more info",
749 type(self.store),
750 exc_info=True,
751 )
752 return self.store.bind(prefix, namespace)
753
754 def bind(
755 self,
756 prefix: Optional[str],
757 namespace: Any,
758 override: bool = True,
759 replace: bool = False,
760 ) -> None:
761 """Bind a given namespace to the prefix
762
763 If override, rebind, even if the given namespace is already
764 bound to another prefix.
765
766 If replace, replace any existing prefix with the new namespace
767 """
768
769 namespace = URIRef(str(namespace))
770 # When documenting explain that override only applies in what cases
771 if prefix is None:
772 prefix = ""
773 elif " " in prefix:
774 raise KeyError("Prefixes may not contain spaces.")
775
776 bound_namespace = self.store.namespace(prefix)
777
778 # Check if the bound_namespace contains a URI
779 # and if so convert it into a URIRef for comparison
780 # This is to prevent duplicate namespaces with the
781 # same URI
782 if bound_namespace:
783 bound_namespace = URIRef(bound_namespace)
784 if bound_namespace and bound_namespace != namespace:
785 if replace:
786 self._store_bind(prefix, namespace, override=override)
787 insert_trie(self.__trie, str(namespace))
788 return
789 # prefix already in use for different namespace
790 #
791 # append number to end of prefix until we find one
792 # that's not in use.
793 if not prefix:
794 prefix = "default"
795
796 num = 1
797 while 1:
798 new_prefix = "%s%s" % (prefix, num)
799 tnamespace = self.store.namespace(new_prefix)
800 if tnamespace and namespace == URIRef(tnamespace):
801 # the prefix is already bound to the correct
802 # namespace
803 return
804 if not self.store.namespace(new_prefix):
805 break
806 num += 1
807 self._store_bind(new_prefix, namespace, override=override)
808 else:
809 bound_prefix = self.store.prefix(namespace)
810 if bound_prefix is None:
811 self._store_bind(prefix, namespace, override=override)
812 elif bound_prefix == prefix:
813 pass # already bound
814 else:
815 if override or bound_prefix.startswith("_"): # or a generated prefix
816 self._store_bind(prefix, namespace, override=override)
817
818 insert_trie(self.__trie, str(namespace))
819
820 def namespaces(self) -> Iterable[Tuple[str, URIRef]]:
821 for prefix, namespace in self.store.namespaces():
822 namespace = URIRef(namespace)
823 yield prefix, namespace
824
825 def absolutize(self, uri: str, defrag: int = 1) -> URIRef:
826 base = Path.cwd().as_uri()
827 result = urljoin("%s/" % base, uri, allow_fragments=not defrag)
828 if defrag:
829 result = urldefrag(result)[0]
830 if not defrag:
831 if uri and uri[-1] == "#" and result[-1] != "#":
832 result = "%s#" % result
833 return URIRef(result)
834
835
836# From: http://www.w3.org/TR/REC-xml#NT-CombiningChar
837#
838# * Name start characters must have one of the categories Ll, Lu, Lo,
839# Lt, Nl.
840#
841# * Name characters other than Name-start characters must have one of
842# the categories Mc, Me, Mn, Lm, or Nd.
843#
844# * Characters in the compatibility area (i.e. with character code
845# greater than #xF900 and less than #xFFFE) are not allowed in XML
846# names.
847#
848# * Characters which have a font or compatibility decomposition
849# (i.e. those with a "compatibility formatting tag" in field 5 of the
850# database -- marked by field 5 beginning with a "<") are not allowed.
851#
852# * The following characters are treated as name-start characters rather
853# than name characters, because the property file classifies them as
854# Alphabetic: [#x02BB-#x02C1], #x0559, #x06E5, #x06E6.
855#
856# * Characters #x20DD-#x20E0 are excluded (in accordance with Unicode
857# 2.0, section 5.14).
858#
859# * Character #x00B7 is classified as an extender, because the property
860# list so identifies it.
861#
862# * Character #x0387 is added as a name character, because #x00B7 is its
863# canonical equivalent.
864#
865# * Characters ':' and '_' are allowed as name-start characters.
866#
867# * Characters '-' and '.' are allowed as name characters.
868
869
870NAME_START_CATEGORIES = ["Ll", "Lu", "Lo", "Lt", "Nl"]
871SPLIT_START_CATEGORIES = NAME_START_CATEGORIES + ["Nd"]
872NAME_CATEGORIES = NAME_START_CATEGORIES + ["Mc", "Me", "Mn", "Lm", "Nd"]
873ALLOWED_NAME_CHARS = ["\u00B7", "\u0387", "-", ".", "_", "%", "(", ")"]
874
875
876# http://www.w3.org/TR/REC-xml-names/#NT-NCName
877# [4] NCName ::= (Letter | '_') (NCNameChar)* /* An XML Name, minus
878# the ":" */
879# [5] NCNameChar ::= Letter | Digit | '.' | '-' | '_' | CombiningChar
880# | Extender
881
882
883def is_ncname(name: str) -> int:
884 if name:
885 first = name[0]
886 if first == "_" or category(first) in NAME_START_CATEGORIES:
887 for i in range(1, len(name)):
888 c = name[i]
889 if not category(c) in NAME_CATEGORIES: # noqa: E713
890 if c in ALLOWED_NAME_CHARS:
891 continue
892 return 0
893 # if in compatibility area
894 # if decomposition(c)!='':
895 # return 0
896
897 return 1
898
899 return 0
900
901
902def split_uri(
903 uri: str, split_start: List[str] = SPLIT_START_CATEGORIES
904) -> Tuple[str, str]:
905 if uri.startswith(XMLNS):
906 return (XMLNS, uri.split(XMLNS)[1])
907 length = len(uri)
908 for i in range(0, length):
909 c = uri[-i - 1]
910 if not category(c) in NAME_CATEGORIES: # noqa: E713
911 if c in ALLOWED_NAME_CHARS:
912 continue
913 for j in range(-1 - i, length):
914 if category(uri[j]) in split_start or uri[j] == "_":
915 # _ prevents early split, roundtrip not generate
916 ns = uri[:j]
917 if not ns:
918 break
919 ln = uri[j:]
920 return (ns, ln)
921 break
922 raise ValueError("Can't split '{}'".format(uri))
923
924
925def insert_trie(
926 trie: Dict[str, Any], value: str
927) -> Dict[str, Any]: # aka get_subtrie_or_insert
928 """Insert a value into the trie if it is not already contained in the trie.
929 Return the subtree for the value regardless of whether it is a new value
930 or not."""
931 if value in trie:
932 return trie[value]
933 multi_check = False
934 for key in tuple(trie.keys()):
935 if len(value) > len(key) and value.startswith(key):
936 return insert_trie(trie[key], value)
937 elif key.startswith(value): # we know the value is not in the trie
938 if not multi_check:
939 trie[value] = {}
940 multi_check = True # there can be multiple longer existing prefixes
941 dict_ = trie.pop(
942 key
943 ) # does not break strie since key<->dict_ remains unchanged
944 trie[value][key] = dict_
945 if value not in trie:
946 trie[value] = {}
947 return trie[value]
948
949
950def insert_strie(strie: Dict[str, Any], trie: Dict[str, Any], value: str) -> None:
951 if value not in strie:
952 strie[value] = insert_trie(trie, value)
953
954
955def get_longest_namespace(trie: Dict[str, Any], value: str) -> Optional[str]:
956 for key in trie:
957 if value.startswith(key):
958 out = get_longest_namespace(trie[key], value)
959 if out is None:
960 return key
961 else:
962 return out
963 return None
964
965
966from rdflib.namespace._BRICK import BRICK
967from rdflib.namespace._CSVW import CSVW
968from rdflib.namespace._DC import DC
969from rdflib.namespace._DCAM import DCAM
970from rdflib.namespace._DCAT import DCAT
971from rdflib.namespace._DCMITYPE import DCMITYPE
972from rdflib.namespace._DCTERMS import DCTERMS
973from rdflib.namespace._DOAP import DOAP
974from rdflib.namespace._FOAF import FOAF
975from rdflib.namespace._GEO import GEO
976from rdflib.namespace._ODRL2 import ODRL2
977from rdflib.namespace._ORG import ORG
978from rdflib.namespace._OWL import OWL
979from rdflib.namespace._PROF import PROF
980from rdflib.namespace._PROV import PROV
981from rdflib.namespace._QB import QB
982from rdflib.namespace._RDF import RDF
983from rdflib.namespace._RDFS import RDFS
984from rdflib.namespace._SDO import SDO
985from rdflib.namespace._SH import SH
986from rdflib.namespace._SKOS import SKOS
987from rdflib.namespace._SOSA import SOSA
988from rdflib.namespace._SSN import SSN
989from rdflib.namespace._TIME import TIME
990from rdflib.namespace._VANN import VANN
991from rdflib.namespace._VOID import VOID
992from rdflib.namespace._WGS import WGS
993from rdflib.namespace._XSD import XSD
994
995# prefixes for the core Namespaces shipped with RDFLib
996_NAMESPACE_PREFIXES_CORE = {
997 "owl": OWL,
998 "rdf": RDF,
999 "rdfs": RDFS,
1000 "xsd": XSD,
1001 # Namespace binding for XML - needed for RDF/XML
1002 "xml": XMLNS,
1003}
1004
1005
1006# prefixes for all the non-core Namespaces shipped with RDFLib
1007_NAMESPACE_PREFIXES_RDFLIB = {
1008 "brick": BRICK,
1009 "csvw": CSVW,
1010 "dc": DC,
1011 "dcat": DCAT,
1012 "dcmitype": DCMITYPE,
1013 "dcterms": DCTERMS,
1014 "dcam": DCAM,
1015 "doap": DOAP,
1016 "foaf": FOAF,
1017 "geo": GEO,
1018 "odrl": ODRL2,
1019 "org": ORG,
1020 "prof": PROF,
1021 "prov": PROV,
1022 "qb": QB,
1023 "schema": SDO,
1024 "sh": SH,
1025 "skos": SKOS,
1026 "sosa": SOSA,
1027 "ssn": SSN,
1028 "time": TIME,
1029 "vann": VANN,
1030 "void": VOID,
1031 "wgs": WGS,
1032}