Repository: cwacek/python-jsonschema-objects

Issue:
Feature request: implement default values
Would it be possible for the auto-generated class to implement any default values as specified in the JSON schema? Right now if I have a property defined as:

```
    "sample-boolean": {
      "description": "A sample boolean",
      "type": "boolean",
      "default": false
    }
```
and I instantiate an object of the generated class using obj = MyClass.from_json('{}') (or any JSON that does not include "sample-boolean") then obj.sample-boolean will be None instead of false.

Implementing the defaults would be a useful feature, I think.

Discussion:

Patch:
diff --git a/python_jsonschema_objects/classbuilder.py b/python_jsonschema_objects/classbuilder.py
index 4ba6006..ed55b99 100644
--- a/python_jsonschema_objects/classbuilder.py
+++ b/python_jsonschema_objects/classbuilder.py
@@ -39,6 +39,7 @@ class ProtocolBase(collections.MutableMapping):
     """
     __propinfo__ = {}
     __required__ = set()
+    __has_default__ = set()
     __object_attr_list__ = set(["_properties", "_extended_properties"])
 
     def as_dict(self):
@@ -158,6 +159,13 @@ class ProtocolBase(collections.MutableMapping):
                                     [None for x in
                                      six.moves.xrange(len(self.__prop_names__))]))
 
+        # To support defaults, we have to actually execute the constructors
+        # but only for the ones that have defaults set.
+        for name in self.__has_default__:
+            if name not in props:
+                logger.debug(util.lazy_format("Initializing '{0}' ", name))
+                setattr(self, name, None)
+
         for prop in props:
             try:
               logger.debug(util.lazy_format("Setting value for '{0}' to {1}", prop, props[prop]))
@@ -166,10 +174,9 @@ class ProtocolBase(collections.MutableMapping):
               import sys
               raise six.reraise(type(e), type(e)(str(e) + " \nwhile setting '{0}' in {1}".format(
                   prop, self.__class__.__name__)), sys.exc_info()[2])
+
         if getattr(self, '__strict__', None):
             self.validate()
-        #if len(props) > 0:
-        #    self.validate()
 
     def __setattr__(self, name, val):
         if name in self.__object_attr_list__:
@@ -277,7 +284,10 @@ class ProtocolBase(collections.MutableMapping):
 def MakeLiteral(name, typ, value, **properties):
     properties.update({'type': typ})
     klass = type(str(name), tuple((LiteralValue,)), {
-        '__propinfo__': {'__literal__': properties}
+        '__propinfo__': {
+            '__literal__': properties,
+            '__default__': properties.get('default')
+        }
     })
 
     return klass(value)
@@ -328,6 +338,9 @@ class LiteralValue(object):
       else:
           self._value = value
 
+      if self._value is None and self.default() is not None:
+          self._value = self.default()
+
       self.validate()
 
   def as_dict(self):
@@ -336,6 +349,10 @@ class LiteralValue(object):
   def for_json(self):
       return self._value
 
+  @classmethod
+  def default(cls):
+      return cls.__propinfo__.get('__default__')
+
   @classmethod
   def propinfo(cls, propname):
       if propname not in cls.__propinfo__:
@@ -516,7 +533,9 @@ class ClassBuilder(object):
 
       """
       cls = type(str(nm), tuple((LiteralValue,)), {
-        '__propinfo__': { '__literal__': clsdata}
+        '__propinfo__': {
+            '__literal__': clsdata,
+            '__default__': clsdata.get('default')}
         })
 
       return cls
@@ -525,6 +544,7 @@ class ClassBuilder(object):
         logger.debug(util.lazy_format("Building object {0}", nm))
 
         props = {}
+        defaults = set()
 
         properties = {}
         for p in parents:
@@ -541,6 +561,9 @@ class ClassBuilder(object):
             name_translation[prop] = prop.replace('@', '')
             prop = name_translation[prop]
 
+            if detail.get('default', None) is not None:
+                defaults.add(prop)
+
             if detail.get('type', None) == 'object':
                 uri = "{0}/{1}_{2}".format(nm,
                                            prop, "<anonymous>")
@@ -673,6 +696,7 @@ class ClassBuilder(object):
                                            .format(nm, invalid_requires))
 
         props['__required__'] = required
+        props['__has_default__'] = defaults
         if required and kw.get("strict"):
             props['__strict__'] = True
         cls = type(str(nm.split('/')[-1]), tuple(parents), props)
@@ -765,7 +789,10 @@ def make_property(prop, info, desc=""):
         elif getattr(info['type'], 'isLiteralClass', False) is True:
             if not isinstance(val, info['type']):
                 validator = info['type'](val)
-            validator.validate()
+                validator.validate()
+                if validator._value is not None:
+                    # This allows setting of default Literal values
+                    val = validator
 
         elif util.safe_issubclass(info['type'], ProtocolBase):
             if not isinstance(val, info['type']):


Test patch:
diff --git a/test/test_pytest.py b/test/test_pytest.py
index 4e52b6f..70dea0e 100644
--- a/test/test_pytest.py
+++ b/test/test_pytest.py
@@ -493,3 +493,27 @@ def test_boolean_in_child_object():
     ns = builder.build_classes()
 
     ns.Test(data={"my_bool": True})
+
+
+
+@pytest.mark.parametrize('default', [
+    '{"type": "boolean", "default": false}',
+    '{"type": "string", "default": "Hello"}',
+    '{"type": "integer", "default": 500}'
+])
+def test_default_values(default):
+    default = json.loads(default)
+    schema = {
+        "$schema": "http://json-schema.org/schema#",
+        "id": "test",
+        "type": "object",
+        "properties": {
+            "sample": default
+        }
+    }
+
+    builder = pjs.ObjectBuilder(schema)
+    ns = builder.build_classes()
+
+    x = ns.Test()
+    assert x.sample == default['default']