Package: schemadict
UsageAschemadictis a regular Python dictionary which specifies the type and format of values for some given key. To check if a test dictionary is conform with the expected schema,schemadictprovides thevalidate()method. If the test dictionary is ill-defined, an error will be thrown, otherwiseNoneis returned.ExamplesBasic usage>>>fromschemadictimportschemadict>>>schema=schemadict({...'name':{...'type':str,...'min_len':3,...'max_len':12,...},...'age':{...'type':int,...'>=':0,...'<':150,...},...})>>>>>>testdict={'name':'Neil','age':55}>>>schema.validate(testdict)>>>>>>testdict={'name':'Neil','age':-12}>>>schema.validate(testdict)Traceback(mostrecentcalllast):...ValueError:'age'toosmall:expected>=0,butwas-12>>>>>>testdict={'name':'Neil','age':'55'}>>>schema.validate(testdict)Traceback(mostrecentcalllast):...TypeError:unexpectedtypefor'age':expected<class'int'>, but was <class 'str'>>>>Nested schemadictIt is possible to check individual item in a list. For instance, in the following example we check if each item (of typestr) looks like a valid IPv4 address. How each item should look like can be specified with theitem_schemakeyword.>>>schema=schemadict({...'ip_addrs':{...'type':list,...'item_schema':{...'type':str,...'regex':r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$',...},...},...})>>>>>>>>>schema.validate({'ip_addrs':['127.0.0.1','192.168.1.1']})# Valid>>>schema.validate({'ip_addrs':['127.0.0.1','192.168.1.1','1234.5678']})# Last item invalidTraceback(mostrecentcalllast):...ValueError:regexmismatchfor'ip_addrs':expectedpattern'^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$',got'1234.5678'>>>Items in alist(ortuple) may themselves be dictionaries which can be described withschemadicts. In this case, we use the keyworditem_schemadictas illustrated in the following example.>>>schema_city=schemadict({...'name':{...'type':str...},...'population':{...'type':int,...'>=':0,...},...})>>>>>>schema_country=schemadict({...'name':{'type':str},...'cities':{...'type':list,...'item_type':dict,...'item_schemadict':schema_city,...},...})>>>>>>test_country={...'name':'Neverland',...'cities':[...{'name':'Faketown','population':3},...{'name':'Evergreen','population':True},...],...}>>>>>>schema_country.validate(test_country)Traceback(mostrecentcalllast):...TypeError:unexpectedtypefor'population':expected<class'int'>, but was <class 'bool'>>>>Custom validation functionsEachtype(int,bool,str, etc.) defines its own set of validation keywords and corresponding test functions. The dictionarySTANDARD_VALIDATORSprovided by theschemadictmodule contains the default validation functions for the Python’s built-in types. However, it is also possible to modify or extend this dictionary with custom validation functions.>>>fromschemadictimportschemadict,STANDARD_VALIDATORS>>># Add a custom validation function>>>defis_divisible(key,value,comp_value,_):...ifvalue%comp_value!=0:...raiseValueError(f"{key!r}is not divisible by{comp_value}").........>>>>>># Update the standard validator dictionary>>>my_validators=STANDARD_VALIDATORS>>>my_validators[int]['%']=is_divisible>>># Register the updated validator dictionary in the new schemadict instance>>>s=schemadict({'my_num':{'type':int,'%':3}},validators=my_validators)>>>s.validate({'my_num':33})>>>s.validate({'my_num':4})Traceback(mostrecentcalllast):...ValueError:'my_num'isnotdivisibleby3>>>It is also possible to definecustom typesandcustom test functionsas shown in the following example.>>>fromschemadictimportschemadict,STANDARD_VALIDATORS>>>classMyOcean:...has_dolphins=True...has_plastic=False...>>>>>>defhas_dolphins(key,value,comp_value,_):...ifgetattr(value,'has_dolphins')isnotcomp_value:...raiseValueError(f"{key!r}does not have dolphins")...>>>>>>my_validators=STANDARD_VALIDATORS>>>my_validators.update({MyOcean:{'has_dolphins':has_dolphins}})>>>>>>schema_ocean=schemadict(...{'ocean':{'type':MyOcean,'has_dolphins':True}},...validators=my_validators,...)>>>>>>ocean1=MyOcean()>>>schema_ocean.validate({'ocean':ocean1})>>>>>>ocean2=MyOcean()>>>ocean2.has_dolphins=False>>>schema_ocean.validate({'ocean':ocean2})Traceback(mostrecentcalllast):...ValueError:'ocean'doesnothavedolphinsFull documentation:https://schemadict.readthedocs.io/FeaturesWhatschemadictoffers:Built-in support for Python’s “primitive types”SpecifyrequiredandoptionalkeysValidatenestedschemasAdd custom validation functions to built-in typesAdd custom validation functions to custom typesSupport for Regex checks of stringsFeatures currently in developmentMetaschema validationLazy validation and summary of all errorsAllow schema variations: schmea 1 OR schema 2InstallationSchemadictis available onPyPIand may simply be installed withpip install schemadictIdeaSchemadictis loosely inspired byJSON schemaandjsonschema, a JSON schema validator for Python.LicenseLicense:Apache-2.0