| 16 | import types |
| 17 | |
| 18 | class Wrapper: |
| 19 | def __init__(self, obj): |
| 20 | self.obj = obj |
| 21 | |
| 22 | def __repr__(self): |
| 23 | return str(self.obj) |
| 24 | |
| 25 | def __getitem__(self, key): |
| 26 | # |
| 27 | # Null key, same as repr of self |
| 28 | # |
| 29 | if not key: |
| 30 | return str(self) |
| 31 | # |
| 32 | # If there is a dereference, split the call |
| 33 | # |
| 34 | rem = None |
| 35 | idx = None |
| 36 | if "." in key: |
| 37 | key, rem = key.split('.', 1) |
| 38 | if '#' in key: |
| 39 | key, idx = key.split('#', 1) |
| 40 | try: |
| 41 | result = getattr(self.obj, key) |
| 42 | except AttributeError: |
| 43 | # |
| 44 | # Allow for last-minute additions to wrappers; if a key doesn't |
| 45 | # exist in the wrapped object, first test ourselves, then delegate |
| 46 | # |
| 47 | if self.__dict__.get(key): |
| 48 | result = self.__dict__[key] |
| 49 | else: |
| 50 | try: |
| 51 | result = self.obj[key] |
| 52 | except: |
| 53 | raise Exception, "Key '%s' (remainder: '%s') not found in object of type %s!" %\ |
| 54 | (key, rem, self.obj.__class__) |
| 55 | except Exception, mesg: |
| 56 | print "Wrapper %s with key %s and remainder %s" % (str(self), key, rem) |
| 57 | print mesg |
| 58 | raise Exception |
| 59 | |
| 60 | # |
| 61 | # If calling a member instance, delegate to it! |
| 62 | # |
| 63 | if type(result) == types.InstanceType: |
| 64 | return Wrapper(result)[rem] |
| 65 | # |
| 66 | # A method could return either another object |
| 67 | # or a result, so delegate the interim result |
| 68 | # |
| 69 | elif type(result) == types.MethodType: |
| 70 | interim = result() |
| 71 | return Wrapper(interim)[rem] |
| 72 | elif idx and type(result) == types.ListType: |
| 73 | return Wrapper(result[int(idx)])[rem] |
| 74 | elif rem: |
| 75 | return Wrapper(result[rem]) |
no outgoing calls
no test coverage detected