Skip to content

Commit fc02817

Browse files
committed
fix: Prevent Collection from add 'rdf:nil rdf:rest rdf:nil.' triples
Creating 'Collection(graph, RDF.nil)' used to add a 'rdf:nil rdf:rest rdf:nil.' triple to the graph, which turned the empty list into an infinite list. This was a side-effect of unconditionally appending 'seq' to the collection, which is not possible when the collection is 'nil' without ill side-effects. This commit makes the append conditional; and also checks the collection is non-empty in case the user explicitly tries to add item to the empty list.
1 parent 0ecc400 commit fc02817

File tree

2 files changed

+19
-2
lines changed

2 files changed

+19
-2
lines changed

rdflib/collection.py

+7-1
Original file line numberDiff line numberDiff line change
@@ -49,12 +49,16 @@ class Collection:
4949
True
5050
>>> c.index(Literal(2)) == 1
5151
True
52+
53+
The collection is immutable if ``uri`` is the empty list
54+
(``http://www.w3.org/1999/02/22-rdf-syntax-ns#nil``).
5255
"""
5356

5457
def __init__(self, graph: Graph, uri: Node, seq: List[Node] = []):
5558
self.graph = graph
5659
self.uri = uri or BNode()
57-
self += seq
60+
if seq:
61+
self += seq
5862

5963
def n3(self) -> str:
6064
"""
@@ -208,6 +212,8 @@ def __iter__(self) -> Iterator[Node]:
208212
return self.graph.items(self.uri)
209213

210214
def _end(self) -> Node:
215+
if self.uri == RDF.nil:
216+
raise ValueError("Cannot append to empty list")
211217
# find end of list
212218
container = self.uri
213219
while True:

test/test_misc/test_collection.py

+12-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
import pytest
44

5-
from rdflib import BNode, Graph, Literal
5+
from rdflib import BNode, Graph, Literal, URIRef
66
from rdflib.collection import Collection
77

88

@@ -39,3 +39,14 @@ def test_scenario() -> None:
3939
c.clear()
4040

4141
assert len(c) == 0
42+
43+
44+
def test_empty_list() -> None:
45+
nil = URIRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#nil")
46+
g = Graph()
47+
48+
c = Collection(g, nil)
49+
50+
assert set(g) == set(), "Collection changed the graph"
51+
52+
assert len(c) == 0

0 commit comments

Comments
 (0)