trafaret.keys — custom Dict keys implementations

class trafaret.keys.KeysSubset(*keys)

From checkers and converters dict must be returned. Some for errors.

>>> from . import extract_error, Mapping, String
>>> cmp_pwds = lambda x: {'pwd': x['pwd'] if x.get('pwd') == x.get('pwd1') else DataError('Not equal')}
>>> d = Dict({KeysSubset('pwd', 'pwd1'): cmp_pwds, 'key1': String})
>>> sorted(d.check({'pwd': 'a', 'pwd1': 'a', 'key1': 'b'}).keys())
['key1', 'pwd']
>>> extract_error(d.check, {'pwd': 'a', 'pwd1': 'c', 'key1': 'b'})
{'pwd': 'Not equal'}
>>> extract_error(d.check, {'pwd': 'a', 'pwd1': None, 'key1': 'b'})
{'pwd': 'Not equal'}
>>> get_values = (lambda d, keys: [d[k] for k in keys if k in d])
>>> join = (lambda d: {'name': ' '.join(get_values(d, ['name', 'last']))})
>>> Dict({KeysSubset('name', 'last'): join}).check({'name': 'Adam', 'last': 'Smith'})
{'name': 'Adam Smith'}
trafaret.keys.confirm_key(name, confirm_name, trafaret)

confirm_key - takes name, confirm_name and trafaret.

Checks if data[‘name’] equals data[‘confirm_name’] and both are valid against trafaret.

trafaret.keys.subdict(name, *keys, **kw)

Subdict key.

Takes a name, any number of keys as args and keyword argument trafaret. Use it like:

def check_passwords_equal(data):
    if data['password'] != data['password_confirm']:
        return t.DataError('Passwords are not equal')
    return data['password']

passwords_key = subdict(
    t.Key('password', trafaret=check_password),
    t.Key('password_confirm', trafaret=check_password),

signup_trafaret = t.Dict(
    t.Key('email', trafaret=t.Email),
trafaret.keys.xor_key(first, second, trafaret)

xor_key - takes first and second key names and trafaret.

Checks if we have only first or only second in data, not both, and at least one.

Then checks key value against trafaret.