[Python-Dev] type categories

Nathan Clegg nathan@geerbox.com
Fri, 23 Aug 2002 09:33:13 -0700

This discussion appears about over, but I haven't seen any solutions
via inheritance.  Other languages that lack true interfaces use
abstract base classes.  Python supports multiple inheritance.  Isn't
this enough?

If the basic types are turned into abstract base classes and inserted
into the builtin name space, and library and user-defined classes are
reparented to the appropriate base class, then isinstance becomes the
test for category inclusion.

A partial example:

class FileType():
      def __init__(*args, **kwargs):
	  raise AbstractClassError, \
		"You cannot instantiate abstract classes"

      def readline(*args, **kwargs):
	  raise NotImplementedError, \
		"Methods must be overridden by their children"

All "file-like" objects, beginning with file itself and StringIO, can
extend FileType (or AbstractFile or File or whatever).  A function
expecting a file-like object or a filename can test the parameter to
see if it is an instance of FileType rather than seeing if it has a
readline method.

Type hierarchies could be obvious (or endlessly debated):

Object --> Collection --> Sequence --> List
      \              \            \--> Tuple
      \              \            \--> String
      \              \--> Set
      \              \--> Mapping  --> Dict
      \--> FileLike   --> File
                     \--> StringIO
      \--> Number     --> Complex
                     \--> Real     --> Integer --> Long
                                  \--> Float
      \--> Iterator
      \--> Iterable


The hierarchy could be further complicated with mutability
(MutableSequence (e.g. list), ImmutableSequence (e.g. tuple, string)),
or perhaps mutability could be a property of classes or even objects
(allowing runtime marking of objects read-only? by contract? enforced?).

This seems to be a library (not language) solution to the problem
posed.  Can the low level types implemented completely in C still
descend from a python parent class without any performance hit? Can
someone please point out the inferiority or infeasibility of this
method?  Or is it just "ugly"?

Nathan Clegg