Source code

Download source archive ↓

src/rdflib/collection.py

1from __future__ import annotations
2
3from typing import TYPE_CHECKING, Iterable, Iterator, List, Optional
4
5from rdflib.namespace import RDF
6from rdflib.term import BNode, Node
7
8if TYPE_CHECKING:
9    from rdflib.graph import Graph
10
11__all__ = ["Collection"]
12
13
14class Collection:
15    """See "Emulating container types": <https://docs.python.org/reference/datamodel.html#emulating-container-types>
16
17    ```python
18    >>> from rdflib.term import Literal
19    >>> from rdflib.graph import Graph
20    >>> from pprint import pprint
21    >>> listname = BNode()
22    >>> g = Graph('Memory')
23    >>> listItem1 = BNode()
24    >>> listItem2 = BNode()
25    >>> g.add((listname, RDF.first, Literal(1))) # doctest: +ELLIPSIS
26    <Graph identifier=... (<class 'rdflib.graph.Graph'>)>
27    >>> g.add((listname, RDF.rest, listItem1)) # doctest: +ELLIPSIS
28    <Graph identifier=... (<class 'rdflib.graph.Graph'>)>
29    >>> g.add((listItem1, RDF.first, Literal(2))) # doctest: +ELLIPSIS
30    <Graph identifier=... (<class 'rdflib.graph.Graph'>)>
31    >>> g.add((listItem1, RDF.rest, listItem2)) # doctest: +ELLIPSIS
32    <Graph identifier=... (<class 'rdflib.graph.Graph'>)>
33    >>> g.add((listItem2, RDF.rest, RDF.nil)) # doctest: +ELLIPSIS
34    <Graph identifier=... (<class 'rdflib.graph.Graph'>)>
35    >>> g.add((listItem2, RDF.first, Literal(3))) # doctest: +ELLIPSIS
36    <Graph identifier=... (<class 'rdflib.graph.Graph'>)>
37    >>> c = Collection(g,listname)
38    >>> pprint([term.n3() for term in c])
39    ['"1"^^<http://www.w3.org/2001/XMLSchema#integer>',
40     '"2"^^<http://www.w3.org/2001/XMLSchema#integer>',
41     '"3"^^<http://www.w3.org/2001/XMLSchema#integer>']
42    >>> Literal(1) in c
43    True
44    >>> len(c)
45    3
46    >>> c._get_container(1) == listItem1
47    True
48    >>> c.index(Literal(2)) == 1
49    True
50
51    ```
52
53    The collection is immutable if `uri` is the empty list (`http://www.w3.org/1999/02/22-rdf-syntax-ns#nil`).
54    """
55
56    def __init__(self, graph: Graph, uri: Node, seq: List[Node] = []):
57        self.graph = graph
58        self.uri = uri or BNode()
59        if seq:
60            self += seq
61
62    def n3(self) -> str:
63        """
64        ```python
65        >>> from rdflib.term import Literal
66        >>> from rdflib.graph import Graph
67        >>> listname = BNode()
68        >>> g = Graph('Memory')
69        >>> listItem1 = BNode()
70        >>> listItem2 = BNode()
71        >>> g.add((listname, RDF.first, Literal(1))) # doctest: +ELLIPSIS
72        <Graph identifier=... (<class 'rdflib.graph.Graph'>)>
73        >>> g.add((listname, RDF.rest, listItem1)) # doctest: +ELLIPSIS
74        <Graph identifier=... (<class 'rdflib.graph.Graph'>)>
75        >>> g.add((listItem1, RDF.first, Literal(2))) # doctest: +ELLIPSIS
76        <Graph identifier=... (<class 'rdflib.graph.Graph'>)>
77        >>> g.add((listItem1, RDF.rest, listItem2)) # doctest: +ELLIPSIS
78        <Graph identifier=... (<class 'rdflib.graph.Graph'>)>
79        >>> g.add((listItem2, RDF.rest, RDF.nil)) # doctest: +ELLIPSIS
80        <Graph identifier=... (<class 'rdflib.graph.Graph'>)>
81        >>> g.add((listItem2, RDF.first, Literal(3))) # doctest: +ELLIPSIS
82        <Graph identifier=... (<class 'rdflib.graph.Graph'>)>
83        >>> c = Collection(g, listname)
84        >>> print(c.n3()) #doctest: +NORMALIZE_WHITESPACE
85        ( "1"^^<http://www.w3.org/2001/XMLSchema#integer>
86            "2"^^<http://www.w3.org/2001/XMLSchema#integer>
87            "3"^^<http://www.w3.org/2001/XMLSchema#integer> )
88
89        ```
90        """
91        return "( %s )" % (" ".join([i.n3() for i in self]))
92
93    def _get_container(self, index: int) -> Optional[Node]:
94        """Gets the first, rest holding node at index."""
95        assert isinstance(index, int)
96        graph = self.graph
97        container: Optional[Node] = self.uri
98        i = 0
99        while i < index:
100            i += 1
101            container = graph.value(container, RDF.rest)
102            if container is None:
103                break
104        return container
105
106    def __len__(self) -> int:
107        """length of items in collection."""
108        return len(list(self.graph.items(self.uri)))
109
110    def index(self, item: Node) -> int:
111        """
112        Returns the 0-based numerical index of the item in the list
113        """
114        listname = self.uri
115        index = 0
116        while True:
117            if (listname, RDF.first, item) in self.graph:
118                return index
119            else:
120                newlink = list(self.graph.objects(listname, RDF.rest))
121                index += 1
122                if newlink == [RDF.nil]:
123                    raise ValueError("%s is not in %s" % (item, self.uri))
124                elif not newlink:
125                    raise Exception("Malformed RDF Collection: %s" % self.uri)
126                else:
127                    assert len(newlink) == 1, "Malformed RDF Collection: %s" % self.uri
128                    listname = newlink[0]
129
130    def __getitem__(self, key: int) -> Node:
131        """TODO"""
132        c = self._get_container(key)
133        if c:
134            v = self.graph.value(c, RDF.first)
135            if v:
136                return v
137            else:
138                raise KeyError(key)
139        else:
140            raise IndexError(key)
141
142    def __setitem__(self, key: int, value: Node) -> None:
143        """TODO"""
144        c = self._get_container(key)
145        if c:
146            self.graph.set((c, RDF.first, value))
147        else:
148            raise IndexError(key)
149
150    def __delitem__(self, key: int) -> None:
151        """
152        ```python
153        >>> from rdflib.namespace import RDF, RDFS
154        >>> from rdflib import Graph
155        >>> from pprint import pformat
156        >>> g = Graph()
157        >>> a = BNode('foo')
158        >>> b = BNode('bar')
159        >>> c = BNode('baz')
160        >>> g.add((a, RDF.first, RDF.type)) # doctest: +ELLIPSIS
161        <Graph identifier=... (<class 'rdflib.graph.Graph'>)>
162        >>> g.add((a, RDF.rest, b)) # doctest: +ELLIPSIS
163        <Graph identifier=... (<class 'rdflib.graph.Graph'>)>
164        >>> g.add((b, RDF.first, RDFS.label)) # doctest: +ELLIPSIS
165        <Graph identifier=... (<class 'rdflib.graph.Graph'>)>
166        >>> g.add((b, RDF.rest, c)) # doctest: +ELLIPSIS
167        <Graph identifier=... (<class 'rdflib.graph.Graph'>)>
168        >>> g.add((c, RDF.first, RDFS.comment)) # doctest: +ELLIPSIS
169        <Graph identifier=... (<class 'rdflib.graph.Graph'>)>
170        >>> g.add((c, RDF.rest, RDF.nil)) # doctest: +ELLIPSIS
171        <Graph identifier=... (<class 'rdflib.graph.Graph'>)>
172        >>> len(g)
173        6
174        >>> def listAncestry(node, graph):
175        ...   for i in graph.subjects(RDF.rest, node):
176        ...     yield i
177        >>> [str(node.n3())
178        ...   for node in g.transitiveClosure(listAncestry, RDF.nil)]
179        ['_:baz', '_:bar', '_:foo']
180        >>> lst = Collection(g, a)
181        >>> len(lst)
182        3
183        >>> b == lst._get_container(1)
184        True
185        >>> c == lst._get_container(2)
186        True
187        >>> del lst[1]
188        >>> len(lst)
189        2
190        >>> len(g)
191        4
192
193        ```
194        """
195        self[key]  # to raise any potential key exceptions
196        graph = self.graph
197        current = self._get_container(key)
198        assert current
199        if len(self) == 1 and key > 0:
200            pass
201        elif key == len(self) - 1:
202            # the tail
203            priorlink = self._get_container(key - 1)
204            # type error: Argument 1 to "set" of "Graph" has incompatible type "Tuple[Optional[Node], URIRef, URIRef]"; expected "Tuple[Node, Node, Any]"
205            self.graph.set((priorlink, RDF.rest, RDF.nil))  # type: ignore[arg-type]
206            graph.remove((current, None, None))
207        else:
208            next = self._get_container(key + 1)
209            prior = self._get_container(key - 1)
210            assert next and prior
211            graph.remove((current, None, None))
212            graph.set((prior, RDF.rest, next))
213
214    def __iter__(self) -> Iterator[Node]:
215        """Iterator over items in Collections"""
216        return self.graph.items(self.uri)
217
218    def _end(self) -> Node:
219        # find end of list
220        container = self.uri
221        while True:
222            rest = self.graph.value(container, RDF.rest)
223            if rest is None or rest == RDF.nil:
224                return container
225            else:
226                container = rest
227
228    def append(self, item: Node) -> Collection:
229        """
230        ```python
231        >>> from rdflib.term import Literal
232        >>> from rdflib.graph import Graph
233        >>> listname = BNode()
234        >>> g = Graph()
235        >>> c = Collection(g,listname,[Literal(1),Literal(2)])
236        >>> links = [
237        ...     list(g.subjects(object=i, predicate=RDF.first))[0] for i in c]
238        >>> len([i for i in links if (i, RDF.rest, RDF.nil) in g])
239        1
240
241        ```
242        """
243        end = self._end()
244        if end == RDF.nil:
245            raise ValueError("Cannot append to empty list")
246
247        if (end, RDF.first, None) in self.graph:
248            # append new node to the end of the linked list
249            node = BNode()
250            self.graph.set((end, RDF.rest, node))
251            end = node
252
253        self.graph.add((end, RDF.first, item))
254        self.graph.add((end, RDF.rest, RDF.nil))
255        return self
256
257    def __iadd__(self, other: Iterable[Node]):
258        end = self._end()
259        if end == RDF.nil:
260            raise ValueError("Cannot append to empty list")
261        self.graph.remove((end, RDF.rest, None))
262
263        for item in other:
264            if (end, RDF.first, None) in self.graph:
265                nxt = BNode()
266                self.graph.add((end, RDF.rest, nxt))
267                end = nxt
268
269            self.graph.add((end, RDF.first, item))
270
271        self.graph.add((end, RDF.rest, RDF.nil))
272        return self
273
274    def clear(self):
275        container: Optional[Node] = self.uri
276        graph = self.graph
277        while container:
278            rest = graph.value(container, RDF.rest)
279            graph.remove((container, RDF.first, None))
280            graph.remove((container, RDF.rest, None))
281            container = rest
282        return self