[Python-Dev] type categories

Andrew Koenig ark@research.att.com
Tue, 13 Aug 2002 14:02:27 -0400 (EDT)


While I was driving to work today, I had a thought about the
iterator/iterable discussion of a few weeks ago.  My impression is
that that discussion was inconclusive, but a few general principles
emerged from it:

	1) Some types are iterators -- that is, they support calls
	   to next() and raise StopIteration when they have no more
	   information to give.

	2) Some types are iterables -- that is, they support calls
	   to __iter__() that yield an iterator as the result.

	3) Every iterator is also an iterable, because iterators are
	   required to implement __iter__() as well as next().

	4) The way to determine whether an object is an iterator
	   is to call its next() method and see what happens.

	5) The way to determine whether an object is an iterable
	   is to call its __iter__() method and see what happens.

I'm uneasy about (4) because if an object is an iterator, calling its
next() method is destructive.  The implication is that you had better
not use this method to test if an object is an iterator until you are
ready to take irrevocable action based on that test.  On the other
hand, calling __iter__() is safe, which means that you can test
nondestructively whether an object is an iterable, which includes
all iterators.

Here is what I realized this morning.  It may be obvious to you,
but it wasn't to me (until after I realized it, of course):

     ``iterator'' and ``iterable'' are just two of many type
     categories that exist in Python.

Some other categories:

     callable
     sequence
     generator
     class
     instance
     type
     number
     integer
     floating-point number
     complex number
     mutable
     tuple
     mapping
     method
     built-in

As far as I know, there is no uniform method of determining into which
category or categories a particular object falls.  Of course, there
are non-uniform ways of doing so, but in general, those ways are, um,
nonuniform.  Therefore, if you want to check whether an object is in
one of these categories, you haven't necessarily learned much about
how to check if it is in a different one of these categories.

So what I wonder is this:  Has there been much thought about making
these type categories more explicitly part of the type system?