Skip to content
Merged
11 changes: 10 additions & 1 deletion rdflib/collection.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,12 +49,16 @@ class Collection:
True
>>> c.index(Literal(2)) == 1
True

The collection is immutable if ``uri`` is the empty list
(``http://www.w3.org/1999/02/22-rdf-syntax-ns#nil``).
"""

def __init__(self, graph: Graph, uri: Node, seq: List[Node] = []):
self.graph = graph
self.uri = uri or BNode()
self += seq
if seq:
self += seq

def n3(self) -> str:
"""
Expand Down Expand Up @@ -232,6 +236,9 @@ def append(self, item: Node) -> Collection:
"""

end = self._end()
if end == RDF.nil:
raise ValueError("Cannot append to empty list")

if (end, RDF.first, None) in self.graph:
# append new node to the end of the linked list
node = BNode()
Expand All @@ -244,6 +251,8 @@ def append(self, item: Node) -> Collection:

def __iadd__(self, other: Iterable[Node]):
end = self._end()
if end == RDF.nil:
raise ValueError("Cannot append to empty list")
self.graph.remove((end, RDF.rest, None))

for item in other:
Expand Down
13 changes: 12 additions & 1 deletion test/test_misc/test_collection.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import pytest

from rdflib import BNode, Graph, Literal
from rdflib import BNode, Graph, Literal, URIRef
from rdflib.collection import Collection


Expand Down Expand Up @@ -39,3 +39,14 @@ def test_scenario() -> None:
c.clear()

assert len(c) == 0


def test_empty_list() -> None:
nil = URIRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#nil")
g = Graph()

c = Collection(g, nil)

assert set(g) == set(), "Collection changed the graph"

assert len(c) == 0