[Python-Dev] Updated Monkey Typing pre-PEP
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