Created
January 1, 2015 03:04
-
-
Save eugene-eeo/849eab3134bed48a4f0f to your computer and use it in GitHub Desktop.
Schema Analysis for TinyDB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from schema import Schema | |
s = Schema.from_iterable([ | |
{'key': True, 'maybe': 1}, | |
{'key': None, 'maybe': True}, | |
{'key': False}, | |
]) | |
print(s) | |
# => {'key': <Key [bool]>, 'maybe': <Maybe [bool, int]>} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def clsname(obj): | |
return obj.__name__ | |
class Schema(dict): | |
def __init__(self, initial): | |
for key, value in initial.items(): | |
self[key] = Key([type(value)]) | |
def update(self, v): | |
keys = set(v).union(self) | |
for key in keys: | |
if key not in v: | |
self[key] = Maybe.from_key(self[key]) | |
continue | |
if key not in self: | |
self[key] = Maybe([]) | |
self[key].add_obj(v[key]) | |
@classmethod | |
def from_iterable(cls, it): | |
it = iter(it) | |
self = cls(next(it)) | |
for item in it: | |
self.update(item) | |
return self | |
class Key(object): | |
def __init__(self, types): | |
self.types = set(types) | |
def add_obj(self, obj): | |
self.types.add(type(obj)) | |
def __repr__(self): | |
return '<%s [%s]>' % ( | |
clsname(self.__class__), | |
', '.join([clsname(i) for i in self.types]), | |
) | |
class Maybe(Key): | |
@classmethod | |
def from_key(cls, key): | |
return Maybe(key.types) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
That's great, thanks!