summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--rdflib/plugins/sparql/sparql.py21
-rw-r--r--test/test_sparql.py19
2 files changed, 30 insertions, 10 deletions
diff --git a/rdflib/plugins/sparql/sparql.py b/rdflib/plugins/sparql/sparql.py
index f24aa564..a98bfb4c 100644
--- a/rdflib/plugins/sparql/sparql.py
+++ b/rdflib/plugins/sparql/sparql.py
@@ -52,12 +52,12 @@ class Bindings(MutableMapping):
self.outer = outer
def __getitem__(self, key):
- try:
+ if key in self._d:
return self._d[key]
- except KeyError:
- if not self.outer:
- raise
- return self.outer[key]
+
+ if not self.outer:
+ raise KeyError()
+ return self.outer[key]
def __contains__(self, key):
try:
@@ -72,17 +72,18 @@ class Bindings(MutableMapping):
def __delitem__(self, key):
raise Exception("DelItem is not implemented!")
- def __len__(self):
+ def __len__(self) -> int:
i = 0
- for x in self:
- i += 1
+ d = self
+ while d is not None:
+ i += len(d._d)
+ d = d.outer
return i
def __iter__(self):
d = self
while d is not None:
- for i in dict.__iter__(d._d):
- yield i
+ yield from d._d
d = d.outer
def __str__(self):
diff --git a/test/test_sparql.py b/test/test_sparql.py
index fdf29c3c..cabb9411 100644
--- a/test/test_sparql.py
+++ b/test/test_sparql.py
@@ -1,3 +1,4 @@
+from rdflib.plugins.sparql import sparql
from rdflib import Graph, URIRef, Literal, BNode
from rdflib.plugins.sparql import prepareQuery
from rdflib.compare import isomorphic
@@ -112,6 +113,24 @@ def test_sparql_update_with_bnode_serialize_parse():
assert not raised
+def test_bindings():
+ layer_0 = sparql.Bindings(d={"v": 1, "bar": 2})
+ layer_1 = sparql.Bindings(outer=layer_0, d={"v": 3})
+
+
+ assert layer_0["v"] == 1
+ assert layer_1["v"] == 3
+ assert layer_1["bar"] == 2
+
+ assert "foo" not in layer_0
+ assert "v" in layer_0
+ assert "bar" in layer_1
+
+ # XXX This might not be intendet behaviour
+ # but is kept for compatibility for now.
+ assert len(layer_1) == 3
+
+
if __name__ == "__main__":
import nose