from jsonschema import validators, Draft7Validator
import jsonschema

def extend_with_default(validator_class):
  validate_properties = validator_class.VALIDATORS["properties"]

  def set_defaults(validator, properties, instance, schema):
    #print properties
    for property, subschema in properties.iteritems():
      #print str(property) + " " + str(subschema)
      if "default" in subschema:
	instance.setdefault(property, subschema["default"])

    return validate_properties(validator, properties, instance, schema)
    #print val
    #for error in val:
    #  yield error

  return validators.extend(validator_class, {"properties" : set_defaults})

DefaultValidatingDraft7Validator = extend_with_default(Draft7Validator)

def validate(instance, schema):
  return DefaultValidatingDraft7Validator(schema).validate(instance)
  #return jsonschema.validate(instance=instance, schema=schema, cls=DefaultValidatingDraft7Validator)
