Skip to content

Commit

Permalink
Merge pull request #1349 from shreyasnagare/fix-graph-operator-overlo…
Browse files Browse the repository at this point in the history
…ading

Update graph operator overloading for subclasses
  • Loading branch information
nicholascar authored Jul 2, 2021
2 parents e4d975a + d605a70 commit 3783df5
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 3 deletions.
15 changes: 12 additions & 3 deletions rdflib/graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -558,7 +558,10 @@ def __isub__(self, other):
def __add__(self, other):
"""Set-theoretic union
BNode IDs are not changed."""
retval = Graph()
try:
retval = type(self)()
except TypeError:
retval = Graph()
for (prefix, uri) in set(list(self.namespaces()) + list(other.namespaces())):
retval.bind(prefix, uri)
for x in self:
Expand All @@ -570,7 +573,10 @@ def __add__(self, other):
def __mul__(self, other):
"""Set-theoretic intersection.
BNode IDs are not changed."""
retval = Graph()
try:
retval = type(self)()
except TypeError:
retval = Graph()
for x in other:
if x in self:
retval.add(x)
Expand All @@ -579,7 +585,10 @@ def __mul__(self, other):
def __sub__(self, other):
"""Set-theoretic difference.
BNode IDs are not changed."""
retval = Graph()
try:
retval = type(self)()
except TypeError:
retval = Graph()
for x in self:
if x not in other:
retval.add(x)
Expand Down
27 changes: 27 additions & 0 deletions test/test_graph_operator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
from rdflib import Graph


class MyGraph(Graph):
def my_method(self):
pass


def test_subclass_add_operator():
g = MyGraph()

g = g + g
assert "my_method" in dir(g)


def test_subclass_sub_operator():
g = MyGraph()

g = g - g
assert "my_method" in dir(g)


def test_subclass_mul_operator():
g = MyGraph()

g = g * g
assert "my_method" in dir(g)

0 comments on commit 3783df5

Please sign in to comment.