Project 1 · Practice
Quiz & exercises
Answer each question to see the explanation. Your best score is saved in this browser.
Quiz
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 ✓ Passed
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.
def key_mismatches(data, template, path=''):
missing = template.keys() - data.keys()
extra = data.keys() - template.keys()
return missing, extra
def test_no_mismatch():
"""matching keys give two empty sets (values ignored)"""
r = key_mismatches({'a': 'x', 'b': {}}, {'a': int, 'b': int}, 'p')
assert r == (set(), set()), r
def test_missing_with_path():
"""missing keys are prefixed with the path"""
r = key_mismatches({'a': 1}, {'a': int, 'b': int, 'c': int}, 'some.path')
assert r == ({'some.path.b', 'some.path.c'}, set()), r
def test_extra_with_path():
"""extra keys are prefixed with the path"""
r = key_mismatches({'a': 1, 'z': 0}, {'a': int}, 'bio')
assert r == (set(), {'bio.z'}), r
def test_both():
"""missing and extra together"""
r = key_mismatches({'a': 1}, {'b': int}, 'x.y')
assert r == ({'x.y.b'}, {'x.y.a'}), r
def test_top_level():
"""no leading dot at the top level"""
r = key_mismatches({'a': 1}, {'b': int})
assert r == ({'b'}, {'a'}), r
def test_non_string_keys():
"""non-string keys are converted to str"""
r = key_mismatches({1: 'x'}, {2: int})
assert r == ({'2'}, {'1'}), r
r = key_mismatches({1: 'x'}, {2: int}, 'n')
assert r == ({'n.2'}, {'n.1'}), r
def test_return_types():
"""returns a tuple of two sets"""
r = key_mismatches({}, {})
assert isinstance(r, tuple) and len(r) == 2
assert all(type(s) is set for s in r), r
Hints (2)
- The starter finds the right keys already; it just doesn't turn them into paths.
- Write a helper
join_path(path, key)that returnsstr(key)whenpathis empty andf'{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 ✓ Passed
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').
def validate(data, template):
if data.keys() != template.keys():
return False, 'mismatched keys'
return True, ''
template = {
'user_id': int,
'name': {'first': str, 'last': str},
'bio': {
'dob': {'year': int, 'month': int, 'day': int},
'birthplace': {'country': str, 'city': str},
},
}
def person(**changes):
p = {
'user_id': 100,
'name': {'first': 'Ada', 'last': 'Lovelace'},
'bio': {
'dob': {'year': 1815, 'month': 12, 'day': 10},
'birthplace': {'country': 'United Kingdom', 'city': 'London'},
},
}
p.update(changes)
return p
def test_valid():
"""valid data"""
assert validate(person(), template) == (True, ''), validate(person(), template)
def test_missing_nested_key():
"""missing key deep in the structure"""
p = person()
del p['bio']['birthplace']['city']
r = validate(p, template)
assert r == (False, 'mismatched keys: bio.birthplace.city'), r
def test_bad_nested_type():
"""wrong type deep in the structure"""
p = person()
p['bio']['dob']['month'] = 'December'
r = validate(p, template)
assert r == (False, 'bad type: bio.dob.month'), r
def test_extra_top_level():
"""extra key at the top level, no leading dot"""
r = validate(person(admin=True), template)
assert r == (False, 'mismatched keys: admin'), r
def test_sorted_mismatches():
"""all mismatched keys at a level, sorted"""
data = {'name': {}, 'bio': {}, 'y': 0, 'x': 0}
r = validate(data, template)
assert r == (False, 'mismatched keys: user_id, x, y'), r
def test_scalar_instead_of_dict():
"""a scalar where a nested template is expected"""
r = validate(person(name='Ada Lovelace'), template)
assert r == (False, 'bad type: name'), r
def test_template_order():
"""the first problem in template order wins"""
p = person(user_id='100')
p['bio']['dob']['day'] = 'ten'
r = validate(p, template)
assert r == (False, 'bad type: user_id'), r
def test_depth_first():
"""a nested dict is validated fully before the next key"""
p = person()
p['name']['last'] = 42
p['bio'] = 'unknown'
r = validate(p, template)
assert r == (False, 'bad type: name.last'), r
def test_keys_before_types():
"""key problems at a level are reported before type problems"""
p = person(user_id='x')
del p['bio']
r = validate(p, template)
assert r == (False, 'mismatched keys: bio'), r
def test_type_tuple_and_flat():
"""flat templates and tuples of types work too"""
t = {'n': (int, float), 's': str}
assert validate({'n': 1.5, 's': ''}, t) == (True, '')
assert validate({'n': '1', 's': ''}, t) == (False, 'bad type: n')
Hints (3)
- Write a recursive helper that takes the current
pathas a third argument, and havevalidatecall it with''. - Compare keys with keys-view differences first. Only then loop over
template.items(); after the key check,data[key]is safe. - 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 ✓ Passed
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.
class SchemaError(Exception):
pass
class SchemaKeyMismatch(SchemaError):
pass
class SchemaTypeMismatch(SchemaError):
pass
def check(data, template):
if data.keys() != template.keys():
raise SchemaError('mismatched keys')
template = {
'user_id': int,
'name': {'first': str, 'last': str},
'bio': {
'dob': {'year': int, 'month': int, 'day': int},
'birthplace': {'country': str, 'city': str},
},
}
def person():
return {
'user_id': 100,
'name': {'first': 'Ada', 'last': 'Lovelace'},
'bio': {
'dob': {'year': 1815, 'month': 12, 'day': 10},
'birthplace': {'country': 'United Kingdom', 'city': 'London'},
},
}
def raised(data):
try:
check(data, template)
except Exception as ex:
return ex
return None
def test_hierarchy():
"""exception classes have the right bases"""
assert issubclass(SchemaError, Exception)
assert issubclass(SchemaKeyMismatch, SchemaError)
assert issubclass(SchemaTypeMismatch, SchemaError)
assert issubclass(SchemaTypeMismatch, TypeError), "SchemaTypeMismatch should also be a TypeError"
assert not issubclass(SchemaKeyMismatch, TypeError)
def test_valid_returns_none():
"""valid data returns None without raising"""
assert check(person(), template) is None
def test_key_mismatch():
"""missing nested key raises SchemaKeyMismatch"""
p = person()
del p['bio']['birthplace']['city']
ex = raised(p)
assert type(ex) is SchemaKeyMismatch, repr(ex)
assert str(ex) == 'mismatched keys: bio.birthplace.city', str(ex)
def test_type_mismatch():
"""wrong nested type raises SchemaTypeMismatch"""
p = person()
p['bio']['dob']['month'] = 'December'
ex = raised(p)
assert type(ex) is SchemaTypeMismatch, repr(ex)
assert str(ex) == 'bad type: bio.dob.month', str(ex)
def test_caught_as_type_error():
"""type problems can be caught as TypeError"""
p = person()
p['name'] = 'Ada'
try:
check(p, template)
except TypeError as ex:
assert str(ex) == 'bad type: name', str(ex)
else:
assert False, 'no exception raised'
def test_sorted_and_ordered():
"""same ordering rules as Goal 2"""
p = person()
p['zz'] = 1
p['aa'] = 2
ex = raised(p)
assert type(ex) is SchemaKeyMismatch and str(ex) == 'mismatched keys: aa, zz', repr(ex)
p = person()
p['name']['last'] = 42
p['bio']['dob']['day'] = 'ten'
ex = raised(p)
assert type(ex) is SchemaTypeMismatch and str(ex) == 'bad type: name.last', repr(ex)
Hints (2)
- Multiple inheritance works for exceptions too:
class SchemaTypeMismatch(SchemaError, TypeError): pass. - Start from your Goal 2 solution and replace each
return False, messagewith araise. 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, '')