Skip to content

Commit d950242

Browse files
committed
Add a cbd_subject() method
This method determines whether the graph is a Concise Bounded Description and, if it is, for what subject
1 parent defb286 commit d950242

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

rdflib/graph.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1879,6 +1879,22 @@ def add_to_cbd(uri: _SubjectType) -> None:
18791879

18801880
return subgraph
18811881

1882+
def cbd_subject(self) -> Optional[_SubjectType]:
1883+
"""Determine the subject for which the graph is a Concise Bounded Description
1884+
1885+
:return: The subject of the CBD or None
1886+
"""
1887+
roots = set(self.roots())
1888+
if len(roots) != 1:
1889+
# A CBD has exactly one root
1890+
return None
1891+
root = roots.pop()
1892+
1893+
real_cbd = self.cbd(root)
1894+
if not real_cbd.isomorphic(self):
1895+
return None
1896+
1897+
return root
18821898

18831899
_ContextType = Graph
18841900

test/test_graph/test_graph_cbd.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,3 +159,26 @@ def test_cbd_target(rdfs_graph: Graph):
159159

160160
assert result is target
161161
assert expected_result == set(result.triples((None, None, None)))
162+
163+
def test_cbd_subject(get_graph):
164+
g = get_graph
165+
166+
assert g.cbd(EX.R1).cbd_subject() == (
167+
EX.R1
168+
), "cbd_subject() for CBD of EX.R1 should be EX.R1"
169+
assert g.cbd(EX.R2).cbd_subject() == (
170+
EX.R2
171+
), "cbd_subject() for CBD of EX.R2 should be EX.R2"
172+
assert g.cbd(EX.R3).cbd_subject() == (
173+
EX.R3
174+
), "cbd_subject() for CBD of EX.R3 should be EX.R3"
175+
assert g.cbd(EX.R4).cbd_subject() == (
176+
None
177+
), "cbd_subject() for CBD of EX.R4 should be None"
178+
179+
test_g = g.cbd(EX.R1)
180+
test_g.add((EX.R2, EX.propOne, EX.P1))
181+
182+
assert test_g.cbd_subject() is (
183+
None
184+
), "cbd_subject() of graph with an additional subject should be None"

0 commit comments

Comments
 (0)