Skip to content
Merged
12 changes: 11 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 @@ -231,6 +235,9 @@ def append(self, item: Node) -> Collection:

"""

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

end = self._end()
if (end, RDF.first, None) in self.graph:
# append new node to the end of the linked list
Expand All @@ -243,6 +250,9 @@ def append(self, item: Node) -> Collection:
return self

def __iadd__(self, other: Iterable[Node]):
if self.uri == RDF.nil:
raise ValueError("Cannot append to empty list")

end = self._end()
self.graph.remove((end, RDF.rest, None))

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