Project 1 · Practice

Quiz & exercises

Answer each question to see the explanation. Your best score is saved in this browser.

Quiz

1. What does this print?
data = {'a': 1, 'b': 2, 'z': 0}
template = {'a': int, 'b': int, 'c': int}
print(sorted(template.keys() - data.keys()), sorted(data.keys() - template.keys()))
2. Why does the validator sort the mismatched paths before joining them into a message?
3. What does this print?
def expected_type(t):
    return dict if isinstance(t, dict) else t

print(isinstance(True, expected_type(int)),
      isinstance({'x': 1}, expected_type({'first': str})),
      isinstance('Ada', expected_type({'first': str})))
4. Why is the validator written recursively instead of with nested loops?
5. What does this print?
class SchemaError(Exception): pass
class SchemaKeyMismatch(SchemaError): pass
class SchemaTypeMismatch(SchemaError, TypeError): pass

for exc in (SchemaKeyMismatch('k'), SchemaTypeMismatch('t')):
    try:
        raise exc
    except TypeError:
        print('TypeError', exc)
    except SchemaError:
        print('SchemaError', exc)
6. In the recursive walk, why is it safe to write data[key] instead of data.get(key) while looping over the template?
7. Compared with returning (False, message), what is the main advantage of raising an exception from deep inside the recursion?

Coding exercises

Write your code, then press Check (or Shift+Enter) to run the tests. Drafts are saved as you type.

Exercise 1: Goal 1: Mismatched keys at one level

Write key_mismatches(data, template, path='') that compares the keys of one level of two dictionaries and returns a tuple (missing, extra):

- missing: a set of dotted paths of template keys that are not in data; - extra: a set of dotted paths of data keys that are not in template.

A dotted path joins path and the key with a ., except at the top level (path == ''), where it's just the key converted to str. Example: key_mismatches({'a': 1}, {'b': int}, 'x.y') returns ({'x.y.b'}, {'x.y.a'}).

Only compare keys; ignore the values completely.

Hints (2)
  1. The starter finds the right keys already; it just doesn't turn them into paths.
  2. Write a helper join_path(path, key) that returns str(key) when path is empty and f'{path}.{key}' otherwise, and apply it in two set comprehensions.
Show a solution
def join_path(path, key):
    return f'{path}.{key}' if path else str(key)

def key_mismatches(data, template, path=''):
    missing = template.keys() - data.keys()
    extra = data.keys() - template.keys()
    return ({join_path(path, k) for k in missing},
            {join_path(path, k) for k in extra})

Exercise 2: Goal 2: Validate a whole document

Write validate(data, template) that returns (True, '') if data matches template, or (False, message) for the first problem found.

Template values are either a type (match with isinstance) or a nested template dict (the value must be a dict that validates recursively). All template keys are required and extra keys are not allowed.

At each level, in this order:

1. If any keys are missing or extra, return (False, 'mismatched keys: ' + ...) listing all mismatched dotted paths at that level (missing and extra together), sorted and joined with ', '. 2. Then, for each template key in template order: if the value has the wrong type (a non-dict where the template is a dict counts), return (False, 'bad type: <path>'). If the template value is a dict, validate that sub-dictionary completely before moving on to the next key.

Paths are dotted from the top, with no leading dot ('bio.dob.month', 'user_id').

Hints (3)
  1. Write a recursive helper that takes the current path as a third argument, and have validate call it with ''.
  2. Compare keys with keys-view differences first. Only then loop over template.items(); after the key check, data[key] is safe.
  3. For a nested template, check isinstance(value, dict) first, then recurse and return immediately if the recursive call reports a problem.
Show a solution
def join_path(path, key):
    return f'{path}.{key}' if path else str(key)

def _validate(data, template, path):
    missing = {join_path(path, k) for k in template.keys() - data.keys()}
    extra = {join_path(path, k) for k in data.keys() - template.keys()}
    if missing or extra:
        return False, 'mismatched keys: ' + ', '.join(sorted(missing | extra))
    for key, expected in template.items():
        key_path = join_path(path, key)
        value = data[key]
        if isinstance(expected, dict):
            if not isinstance(value, dict):
                return False, f'bad type: {key_path}'
            is_ok, message = _validate(value, expected, key_path)
            if not is_ok:
                return False, message
        elif not isinstance(value, expected):
            return False, f'bad type: {key_path}'
    return True, ''

def validate(data, template):
    return _validate(data, template, '')

Exercise 3: Goal 3: Raise exceptions instead

Define an exception hierarchy and a validator that raises instead of returning status codes:

- SchemaError, a subclass of Exception; - SchemaKeyMismatch, a subclass of SchemaError; - SchemaTypeMismatch, a subclass of both SchemaError and TypeError.

Then write check(data, template), with exactly the same rules and messages as Goal 2's validate, that returns None for valid data, raises SchemaKeyMismatch('mismatched keys: ...') for key problems and raises SchemaTypeMismatch('bad type: ...') for type problems.

Hints (2)
  1. Multiple inheritance works for exceptions too: class SchemaTypeMismatch(SchemaError, TypeError): pass.
  2. Start from your Goal 2 solution and replace each return False, message with a raise. The recursive call no longer needs its result checked.
Show a solution
class SchemaError(Exception):
    pass

class SchemaKeyMismatch(SchemaError):
    pass

class SchemaTypeMismatch(SchemaError, TypeError):
    pass

def join_path(path, key):
    return f'{path}.{key}' if path else str(key)

def _check(data, template, path):
    missing = {join_path(path, k) for k in template.keys() - data.keys()}
    extra = {join_path(path, k) for k in data.keys() - template.keys()}
    if missing or extra:
        raise SchemaKeyMismatch('mismatched keys: ' + ', '.join(sorted(missing | extra)))
    for key, expected in template.items():
        key_path = join_path(path, key)
        value = data[key]
        expected_type = dict if isinstance(expected, dict) else expected
        if not isinstance(value, expected_type):
            raise SchemaTypeMismatch(f'bad type: {key_path}')
        if isinstance(expected, dict):
            _check(value, expected, key_path)

def check(data, template):
    _check(data, template, '')