commonlibs.dicts package

Submodules

commonlibs.dicts.schemadicts module

Schema dictionaries

exception commonlibs.dicts.schemadicts.SchemaError[source]

Bases: Exception

Raised if the schema dictionary is ill-defined

commonlibs.dicts.schemadicts.check_dict_against_schema(test_dict, schema_dict)[source]

Check that a dictionary conforms to a schema dictionary

This function will raise an error if the ‘test_dict’ is not in alignment with the ‘schema_dict’

Args:
schema_dict:Schema dictionary
test_dict:Dictionary to test against schema dictionary
Raises:
KeyError:If test dictionary does not have a required key
SchemaError:If the schema itself is ill-defined
TypeError:If test dictionary has a value of wrong type
ValueError:If test dictionary has a value of wrong ‘size’
Note:
  • Schema validation inspired by JSON schema, see

https://json-schema.org/understanding-json-schema/reference/index.html

commonlibs.dicts.schemadicts.check_keys_in_dict(required_keys, test_dict)[source]

Check that required keys are in a test dictionary

Args:
required_keys:List of keys required in the test dictionary
test_dict:Test dictionary
Raises:
KeyError:If a required key is not found in the test dictionary
commonlibs.dicts.schemadicts.get_default_value_dict(schema_dict)[source]

Return a dictionary with default values based on a schema dict

Default values are genereated as follows:

  • If a key ‘default’ exists, the corresponding value will be used
    • If value is callable object, then the called value will be used
    • If value is non-callable, the value itself will be used
  • If no key, ‘default’ exists, ‘type’ will be called (if callable type)
  • Otherwise the default value will be None

Example:

from datetime import datetime

def time_now():
    return datetime.strftime(datetime.now(), '%H:%S')

schema_dict = {
    'time': {'type': str, 'default': time_now},
    'person': {'type': str, 'default': 'C.Lindbergh'},
    'age': {'type': int},
    'pets': {
        'type': dict,
        'schema': {
            'dog': {'type': bool, 'default': None},
            'cat': {'type': bool}
        },
    },
}

The function will return

defaults = {
    'time': '08:40',
    'person': 'C.Lindbergh',
    'age': 0,
    'pets': {
        'dog': None,
        'cat': False,
    }
}

Module contents