Skip to content

Instantly share code, notes, and snippets.

@hejmsdz
Created February 20, 2018 22:00
Show Gist options
  • Save hejmsdz/30ed8b04af6284f515a4a7dec676eb4e to your computer and use it in GitHub Desktop.
Save hejmsdz/30ed8b04af6284f515a4a7dec676eb4e to your computer and use it in GitHub Desktop.
Data structure format checker
# Simple recursive function that checks the format of a data structure,
# which can consist of dicts, lists, tuples and primitive types.
def check_format(struct, obj):
if isinstance(struct, dict):
return isinstance(obj, dict) and all(check_format(substruct, obj[key]) for key, substruct in struct.items())
if isinstance(struct, tuple):
return isinstance(obj, tuple) and all(check_format(substruct, obj[i]) for i, substruct in enumerate(struct))
elif isinstance(struct, list):
return isinstance(obj, list) and all(check_format(struct[0], item) for item in obj)
elif isinstance(struct, type):
return isinstance(obj, struct)
# Usage example
struct = {"name": str, "score": int, "good": bool, "points": [(float, float)]}
obj = {"name": "goblin", "score": 58, "good": False, "points": [(13.6, 4.2), (7.1, 9.5)]}
print(check_format(struct, obj))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment