Skip to content

Instantly share code, notes, and snippets.

@minimal
Last active December 10, 2015 18:28
Show Gist options
  • Save minimal/4474513 to your computer and use it in GitHub Desktop.
Save minimal/4474513 to your computer and use it in GitHub Desktop.
"""
Turn an example dictionary into a voluptious schema
"""
import pprint
import re
import sys
import voluptuous
test_dict = {
'exclude': ['Users', 'Uptime'],
'include': [],
'set': {
'snmp_community': 'public',
'snmp_timeout': 15,
'snmp_version': '2c',
},
'targets': {
'localhost': {
'exclude': ['Uptime'],
'features': {
'Uptime': {
'retries': 3,
},
'Users': {
'snmp_community': 'monkey',
'snmp_port': 15,
},
},
'include': ['Users'],
'set': {
'snmp_community': 'monkeys',
'myset': {1,2,3,4},
'mytuple': (1,2,3,4)
},
},
},
}
def create_dict_schema(struct):
"""
Arguments:
- `struct`: dictionary
"""
assert isinstance(struct, (dict, list, tuple))
schema = {}
for key, val in struct.iteritems():
if isinstance(val, dict):
sch = create_dict_schema(val) # will blow stack for deep trees
schema[key] = sch
elif isinstance(val, (list, tuple)) and val:
if isinstance(val[0], dict):
sch = create_dict_schema(val[0])
schema[key] = type(val)([sch])
else:
schema[key] = type(val)([type(val[0])])
else:
schema[key] = type(val)
return schema
def doc_to_string(doc):
schema = create_dict_schema(doc)
outstr = pprint.pformat(schema)
return re.sub("<type '(\w+)'>", '\g<1>', outstr)
if __name__ == '__main__':
if len(sys.argv) == 1:
schema = create_dict_schema(test_dict)
outstr = pprint.pformat(schema)
vschema = voluptuous.Schema(schema)
assert vschema(test_dict) == test_dict
print re.sub("<type '(\w+)'>", '\g<1>', outstr)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment