[2187] | 1 | class Record(object): |
---|
| 2 | _identity_field = None |
---|
| 3 | def get(self, field): |
---|
| 4 | try: |
---|
| 5 | return self.__getattribute__(field) |
---|
| 6 | except: |
---|
| 7 | return None |
---|
| 8 | def _formatField(self, field): |
---|
| 9 | v = self.get(field) |
---|
| 10 | if callable(v): |
---|
| 11 | v = v() |
---|
| 12 | if hasattr(v, '__iter__'): |
---|
| 13 | if len(v) == 0: |
---|
| 14 | return '[]' |
---|
| 15 | else: |
---|
| 16 | return '[%d x %s]'%(len(v), type(v[0])) |
---|
| 17 | else: |
---|
| 18 | return repr(v) |
---|
| 19 | def _fields(self): |
---|
| 20 | ignore = self._ignore() |
---|
| 21 | keys = sorted(self.__class__.__dict__.keys()) |
---|
| 22 | return [(k,self._formatField(k)) for k in keys if k[0]!="_" and k not in ignore] |
---|
| 23 | def __repr__(self): |
---|
| 24 | classname = self.__class__.__name__ |
---|
| 25 | |
---|
| 26 | if self._identity_field: |
---|
| 27 | identity = self.__dict__.get(self._identity_field) |
---|
| 28 | identity = ' ' + (identity and repr(identity) or 'hash=%d'%hash(self)) |
---|
| 29 | else: |
---|
| 30 | identity = '' |
---|
| 31 | |
---|
| 32 | payload = " ".join(["%s=%s" % (k, v) for k,v in self._fields()]) |
---|
| 33 | if len(payload) > 0: |
---|
| 34 | payload = ": "+payload |
---|
| 35 | |
---|
| 36 | return "<%s%s%s>" % (classname, identity, payload) |
---|
| 37 | def _ignore(self): |
---|
| 38 | return [self._identity_field, 'c', 'query', 'get'] |
---|
| 39 | |
---|
| 40 | class FormattableRecord(Record): |
---|
| 41 | _format = {} |
---|
| 42 | def _formatField(self, field): |
---|
| 43 | func = self._format.get(field) |
---|
| 44 | if func: |
---|
| 45 | return func(self.get(field)) |
---|
| 46 | else: |
---|
| 47 | return super(FormattableRecord, self)._formatField(field) |
---|
| 48 | |
---|
| 49 | class NullableRecord(FormattableRecord): |
---|
| 50 | _default = {} |
---|
| 51 | def get(self, field): |
---|
| 52 | v = self.__dict__.get(field) |
---|
| 53 | if v != None: |
---|
| 54 | return v |
---|
| 55 | else: |
---|
| 56 | return self._default.get(field) |
---|