[Python-Dev] Updated Monkey Typing pre-PEP (original) (raw)

Raymond Hettinger python at rcn.com
Fri Jan 21 00:21:17 CET 2005


[Guido van Rossum]

There's one other problem that Phillip tries to tackle in his proposal: how to implement the "rich" version of an interface if all you've got is a partial implementation (e.g. you might have readline() but you need readlines()). I think this problem is worthy of a solution, but I think the solution could be found, again, in a traditional adapter class. Here's a sketch::

class RichFile: def init(self, ref): _self.ref = ref if not hasattr(ref, 'readlines'): _self.readlines = self.readlines # Other forms of this magic are conceivably _def readlines(self): # Ignoring the rarely used optional argument _# It's tempting to use [line for line in self.ref] here but that doesn't use readline() lines = [] while True: _line = self.ref.readline() if not line: break lines.append(line) return lines def getattr(self, name): # Delegate all other attributes to the underlying object _return getattr(self.ref, name)

Instead of a getattr solution, I recommend subclassing from a mixin:

class RichMap(SomePartialMapping, UserDict.DictMixin): pass

class RichFile(SomePartialFileClass, Mixins.FileMixin): pass

Raymond



More information about the Python-Dev mailing list