Skip to content

Instantly share code, notes, and snippets.

@eugene-eeo
Created January 1, 2015 03:04
Show Gist options
  • Save eugene-eeo/849eab3134bed48a4f0f to your computer and use it in GitHub Desktop.
Save eugene-eeo/849eab3134bed48a4f0f to your computer and use it in GitHub Desktop.
Schema Analysis for TinyDB
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]>}
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)
@pjakobsen
Copy link

That's great, thanks!

@msiemens
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment