Last change
on this file since 2191 was
2191,
checked in by price, 16 years ago
|
small fixes to Record
|
-
Property svn:executable set to
*
|
File size:
1.7 KB
|
Line | |
---|
1 | class Record(object): |
---|
2 | _identity_field = None |
---|
3 | |
---|
4 | def get(self, field): |
---|
5 | try: |
---|
6 | return self.__getattribute__(field) |
---|
7 | except: |
---|
8 | return None |
---|
9 | |
---|
10 | def _formatField(self, field): |
---|
11 | v = self.get(field) |
---|
12 | if callable(v): |
---|
13 | v = v() |
---|
14 | if hasattr(v, '__iter__'): |
---|
15 | if len(v) == 0: |
---|
16 | return '[]' |
---|
17 | else: |
---|
18 | return '[%d x %s]'%(len(v), type(v[0])) |
---|
19 | else: |
---|
20 | return repr(v) |
---|
21 | |
---|
22 | @classmethod |
---|
23 | def _ignore(cls): |
---|
24 | return [cls._identity_field] |
---|
25 | |
---|
26 | def _fields(self): |
---|
27 | ignore = self._ignore() |
---|
28 | keys = sorted(self.c.keys()) |
---|
29 | return [(k,self._formatField(k)) for k in keys if k not in ignore] |
---|
30 | |
---|
31 | def __repr__(self): |
---|
32 | classname = self.__class__.__name__ |
---|
33 | |
---|
34 | if self._identity_field: |
---|
35 | identity = self.__dict__.get(self._identity_field) |
---|
36 | identity = ' ' + (identity and repr(identity) or 'hash=%d'%hash(self)) |
---|
37 | else: |
---|
38 | identity = '' |
---|
39 | |
---|
40 | payload = " ".join(["%s=%s" % (k, v) for k,v in self._fields()]) |
---|
41 | if len(payload) > 0: |
---|
42 | payload = ": "+payload |
---|
43 | |
---|
44 | return "<%s%s%s>" % (classname, identity, payload) |
---|
45 | |
---|
46 | class FormattableRecord(Record): |
---|
47 | _format = {} |
---|
48 | def _formatField(self, field): |
---|
49 | func = self._format.get(field) |
---|
50 | if func: |
---|
51 | return func(self.get(field)) |
---|
52 | else: |
---|
53 | return super(FormattableRecord, self)._formatField(field) |
---|
54 | |
---|
55 | class NullableRecord(FormattableRecord): |
---|
56 | _default = {} |
---|
57 | def get(self, field): |
---|
58 | v = self.__dict__.get(field) |
---|
59 | if v != None: |
---|
60 | return v |
---|
61 | else: |
---|
62 | return self._default.get(field) |
---|
Note: See
TracBrowser
for help on using the repository browser.