66from jsonschema import validators , Draft4Validator , FormatChecker , ValidationError
77from pkg_resources import resource_filename
88
9+ # helper function that will later be used to tell the schema validator how to validate objects of type "array"
910def is_array (checker , instance ):
1011 return isinstance (instance , (list , np .ndarray ))
1112
1213# Extend the default type checker by redefining "array"
14+ # whenever a schema expects a value of type "array", it will now use the is_array function to check if the value is acceptable.
1315custom_type_checker = Draft4Validator .TYPE_CHECKER .redefine ("array" , is_array )
1416
1517# Create a custom validator that uses the new type checker.
18+ # any validation performed with CustomValidator will use the custom array checker
1619CustomValidator = validators .extend (Draft4Validator , type_checker = custom_type_checker )
1720format_checker = FormatChecker ()
1821
22+ # Define a custom format checker
23+ # called when a JSON schema specifies that a value should have the format "datatype"
1924@format_checker .checks ('datatype' )
2025def is_python_datatype (value ):
2126 """Return whether the given value is a valid data type specification for a NetCDF variable"""
@@ -25,14 +30,19 @@ def is_python_datatype(value):
2530 return issubclass (value , np .number )
2631 return False
2732
33+ # Load JSON schema file
2834TEMPLATE_SCHEMA_JSON = resource_filename (__name__ , 'template_schema.json' )
2935with open (TEMPLATE_SCHEMA_JSON ) as f :
3036 TEMPLATE_SCHEMA = json .load (f )
37+
38+ # Use the custom validator to check it is valid according to Draft 4 rules
3139CustomValidator .check_schema (TEMPLATE_SCHEMA )
3240
33- # Use the custom validator
41+ # ready-to-use validator that applies both custom type and format checks
3442template_validator = CustomValidator (TEMPLATE_SCHEMA , format_checker = format_checker )
3543
44+
45+ # Validation checks
3646def validate_template (t ):
3747 template_validator .validate (t )
3848
0 commit comments