Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import types
- __all__ = ('Field', 'Food')
- class Field(object):
- """A field in a resource enforcing the type of its value"""
- def __init__(self, field_type, doc=None, default=None):
- self._field_type = field_type
- if not isinstance(default, (self._field_type, types.NoneType)):
- raise TypeError(default.__class__)
- self._default_value = default
- if not doc:
- doc = self._field_type.__doc__
- elif isinstance(doc, unicode):
- doc = doc.decode('utf-8')
- self.__doc__ = '%r: %s' % (self._field_type, doc)
- def _set_field_name(self, name):
- self._field_name = name
- def __get__(self, obj, type=None):
- return getattr(obj, self._field_name, self._default_value)
- def __set__(self, obj, value):
- # if someone gives str and we want unicode (or viceversa) handle the
- # conversion automagically, this simplifies a lot
- if self._field_type is unicode and isinstance(value, str):
- value = value.decode('utf-8')
- elif self._field_type is str and isinstance(value, unicode):
- value = value.encode('utf-8')
- elif not isinstance(value, (self._field_type, types.NoneType)):
- raise TypeError('Expected %r, got %r' % (self._field_type,
- value.__class__))
- setattr(obj, self._field_name, value)
- class Food(object):
- """A single resource"""
- def __new__(cls, **kwargs):
- obj = super(Food, cls).__new__(cls)
- fields = []
- for xcls in cls.mro():
- for k,v in xcls.__dict__.iteritems():
- if isinstance(v, Field):
- field_name = '__field_%s' % k
- v._set_field_name(field_name)
- fields.append(k)
- obj._fields = tuple(fields)
- return obj
- def __init__(self, **kwargs):
- super(Food, self).__init__()
- for k,v in kwargs.iteritems():
- if k in self._fields:
- setattr(self, k, v)
- @property
- def kind(self):
- """Kind is not a Field"""
- return self._kind
- def values(self):
- d = dict(zip(self._fields, (getattr(self, k) for k in self._fields)))
- # kind is not a Field, but still it should be present on avery Food
- d['kind'] = self.kind
- return d
- def __str__(self):
- return str(self.values())
- def __eq__(self, other):
- return self.values() == other.values()
Add Comment
Please, Sign In to add comment