[Python-Dev] Simplify the file-like-object interface

Antoine Pitrou solipsis at pitrou.net
Tue Sep 6 15:12:40 CEST 2005

> That sounds like a good idea. I'm certainly getting concerned about
> the proliferation of methods that people "should" add to file-like
> objects, where read/write are the only fundamental ones needed.
> I can't see mixins working, as too many file-like objects are written in C...

One could use "class decorators". For example if you want to define the
method foo() in a file-like class, you could use code like:

def FooExtender(cls):
  class wrapper(cls):
    # Don't do anything if "foo" already defined
  except AttributeError:
    def foo(self):
      """ Automatically generated foo method. """
    wrapper.foo = foo
  return wrapper

MyFileClass = FooExtender(MyCFileClass)

This is for classes, but the construct can be adapted to work on objects

The advantage of using a decorator-like function is that you can do some
complex processing in the function (you could for example automatically
define __ne__ if only __eq__ is defined, and conversely). And it could
probably plug, as an useful convenience or even an automatic mechanism,
into a more sophisticated adaptor system.

More information about the Python-Dev mailing list