[Python-Dev] Class/type dichotomy thoughts

Guido van Rossum guido@python.org
Sun, 05 Nov 2000 21:44:57 -0500

> > - Class/type dichotomy???

> One thing that would probably be implementable is a way to
> maintain "instance" dictionaries for types (which are created
> on-demand whenever an assignment is made).
> This would enable
> extending types with new methods and attributes. "Subclassing"
> could then be emulated by using new contructors which add the
> new or changed methods to each created type instance, e.g.
> class myclose:
>     def __init__(self, object, basemethod):
>         self.object = object
>         self.basemethod = basemethod
>     def __call__(self):
>         print 'Closed file %s' % self.object
>         self.basemethod()
> def myfile(filename):
>     f = open(filename)
>     # add/override attributes
>     f.newattribute = 1
>     # add/override methods
>     f.close = myclose(f, f.close)
>     return f
> Types would have to be made aware of this possibility. Python
> could provide some helping APIs to make life easier for the
> programmer.

But this would require an extra pointer field for *all* built-in
types.  That would seriously impact the space requirements for ints
and floats!

As long as we're proposing hacks like this that don't allow smooth
subclassing yet but let you get at least some of the desired effects,
I'd rather propose to introduce some kind of metaclass that will allow
you to use a class statement to define this.  Thinking aloud:

import types
filemetaclass = metaclass(types.FileType)

class myfile(filemetaclass):

      def __init__(self, filename):
	  self.newattribute = 1

      def close(self):

I'm not quite sure what kind of object "filemetaclass" here should be
or what exactly "metaclass()" should do, but it could create a new
type that has the lay-out of an existing file object, with an instance
dictionary (for newattribute) tacked on the end.  Later maybe (I'm
going to brainstorm with Jim Fulton about types and classes).

--Guido van Rossum (home page: http://www.python.org/~guido/)