Commits

masklinn  committed c8139e5

Implement __getitem__ and get on dicts, fixes issue 7

  • Participants
  • Parent commits cbd4572

Comments (0)

Files changed (2)

         }
     });
     py.list = py.tuple;
-    py.dict = py.type(function dict() {
+    py.dict = py.type(function dict(d) {
         this._store = {};
+        for (var k in (d || {})) {
+            if (!d.hasOwnProperty(k)) { continue; }
+            var py_k = new py.str(k);
+            var val = PY_ensurepy(d[k]);
+            this._store[py_k.__hash__()] = [py_k, val];
+        }
     }, py.object, {
+        __getitem__: function (key) {
+            var h = key.__hash__();
+            if (!(h in this._store)) {
+                throw new Error("KeyError: '" + key.toJSON() + "'");
+            }
+            return this._store[h][1];
+        },
         __setitem__: function (key, value) {
             this._store[key.__hash__()] = [key, value];
         },
+        get: function (args) {
+            var h = args[0].__hash__();
+            var def = args.length > 1 ? args[1] : py.None;
+            if (!(h in this._store)) {
+                return def;
+            }
+            return this._store[h][1];
+        },
         toJSON: function () {
             var out = {};
             for(var k in this._store) {

File test/test.js

         });
     });
 });
+describe('dicts', function () {
+    it('should be possible to retrieve their value', function () {
+        var d = new py.dict({foo: 3, bar: 4, baz: 5});
+        expect(py.eval('d["foo"]', {d: d})).to.be(3);
+        expect(py.eval('d["baz"]', {d: d})).to.be(5);
+    });
+    it('should raise KeyError if a key is missing', function () {
+        var d = new py.dict();
+        expect(function () {
+            py.eval('d["foo"]', {d: d});
+        }).to.throwException(/^KeyError/);
+    });
+    it('should have a method to provide a default value', function () {
+        var d = new py.dict({foo: 3});
+        expect(py.eval('d.get("foo")', {d: d})).to.be(3);
+        expect(py.eval('d.get("bar")', {d: d})).to.be(null);
+        expect(py.eval('d.get("bar", 42)', {d: d})).to.be(42);
+
+        var e = new py.dict({foo: null});
+        expect(py.eval('d.get("foo")', {d: e})).to.be(null);
+        expect(py.eval('d.get("bar")', {d: e})).to.be(null);
+    });
+});
 describe('Type converter', function () {
     it('should convert bare objects to objects', function () {
         expect(py.eval('foo.bar', {foo: {bar: 3}})).to.be(3);