Repository: cwacek/python-jsonschema-objects

Issue:
automatically convert keys in property access
I often use properties of pjs objects as keys in other objects (i.e., dictionary lookup), such as in
```python
o = orgs[handle.key]
```
with `handle` and `orgs` both being instances of `ProtocolBase`.
This, however, does not work since Python expects a string here, and throws a `TypeError`:
```
TypeError: getattr(): attribute name must be string
```

To work around this, I need to call `str()` explicitly, as in:
```python
o = orgs[str(handle.key)]
```
It would be convinient, if the `__getattr__`, `__setattr__`, `__delattr__`, … functions could cast `Literal<str>` to `str` themselves (they could, e.g., always call `str()` unconditionally since the key to lookup an object property must be a string).

Discussion:

Patch:
diff --git a/python_jsonschema_objects/classbuilder.py b/python_jsonschema_objects/classbuilder.py
index 0313909..8178397 100644
--- a/python_jsonschema_objects/classbuilder.py
+++ b/python_jsonschema_objects/classbuilder.py
@@ -213,6 +213,7 @@ class ProtocolBase(collections.MutableMapping):
             self.validate()
 
     def __setattr__(self, name, val):
+        name = str(name)
         if name in self.__object_attr_list__:
             object.__setattr__(self, name, val)
         elif name in self.__propinfo__:
@@ -252,6 +253,7 @@ class ProtocolBase(collections.MutableMapping):
             raise KeyError(key)
 
     def __getattr__(self, name):
+        name = str(name)
         if name in self.__prop_names__:
             raise AttributeError(name)
         if name in self._extended_properties:
@@ -261,12 +263,15 @@ class ProtocolBase(collections.MutableMapping):
         )
 
     def __setitem__(self, key, val):
+        key = str(key)
         return setattr(self, key, val)
 
     def __delitem__(self, key):
+        key = str(key)
         return delattr(self, key)
 
     def __delattr__(self, name):
+        name = str(name)
         if name in self._extended_properties:
             del self._extended_properties[name]
             return


Test patch:
diff --git a/test/test_feature_177.py b/test/test_feature_177.py
new file mode 100644
index 0000000..576aa01
--- /dev/null
+++ b/test/test_feature_177.py
@@ -0,0 +1,38 @@
+import pytest
+
+import python_jsonschema_objects as pjo
+
+
+@pytest.fixture
+def classes():
+
+    schema = {
+        "title": "Config",
+        "type": "object",
+        "additionalProperties": {"$ref": "#/definitions/Parameter"},
+        "definitions": {
+            "Parameter": {
+                "$id": "Parameter",
+                "type": "object",
+                "properties": {
+                    "key": {"type": "string"},
+                    "value": {"oneOf": [{"type": "string"}, {"type": "number"}]},
+                },
+            }
+        },
+    }
+
+    return pjo.ObjectBuilder(schema).build_classes()
+
+
+def test_pjo_objects_can_be_used_as_property_keys(classes):
+    container = classes.Config()
+    obj1 = classes.Parameter(key="volume", value=11)
+    obj2 = classes.Parameter(key="compression", value="on")
+
+    container[obj1.key] = obj1
+    container[obj2.key] = obj2
+
+    assert container.volume.value == 11
+
+    assert sorted(container.keys()) == sorted(str(k) for k in [obj1.key, obj2.key])
diff --git a/test/test_pytest.py b/test/test_pytest.py
index 415101d..2ae8a5e 100644
--- a/test/test_pytest.py
+++ b/test/test_pytest.py
@@ -402,6 +402,19 @@ def test_attribute_set_via_dict(person_object):
     assert str(name) == "John"
 
 
+def test_keys_can_be_other_pjo_objects(Person, person_object):
+    person_object.lastName = "Smith"
+
+    jane = Person(firstName="Jane", lastName=person_object.lastName)
+
+    assert jane.lastName == person_object.lastName
+
+    # We don't want the names to be the same literal object though.
+    # Changing one after assignment should not change the other
+    jane.lastName = "Borges"
+    assert jane.lastName != person_object.lastName
+
+
 def test_numeric_attribute_validation(Person):
     with pytest.raises(pjs.ValidationError):
         Person(firstName="James", lastName="Bond", age=-10)