Booleans, integer division, backwards compatibility; where is Python going?

Thomas Bellman bellman at lysator.liu.se
Wed Apr 10 15:23:44 EDT 2002


Alex Martelli <aleax at aleax.it> wrote:

> Once you're using (e.g.) iterators in your package, or subclassing
> a standard class, there's no extra cost in having the modules of
> your package use (e.g.) generators or true-division as well, so
> why shouldn't a package author freely do so?

For the specific case of iterators, it is fairly easy to add a
backwards compatible interface to your classes, so they work even
in an older interpreter:

    try:
	StopIteration
    except NameError:
	class StopIteration(Exception):
	    pass

    class IteratorEmulator:
	def __getitem__(self, i):
	    if i == 0:
		self.__iterator_index = 0
		self.__iterator = self.__iter__()
	    if self.__iterator_index != i:
		raise IndexError("not indexed sequentially")
	    self.__iterator_index = self.__iterator_index + 1
	    try:
		return self.__iterator.next()
	    except StopIteration:
		raise IndexError("index out of range")

Then just let your classes inherit from IteratorEmulator.  This,
of course, assumes that you don't need __getitem__() for other
purposes, or that you are returning infinite sequences.

Generators, inheriting from builtin types, and true division, are
not as easy to get running in an older interpreter, so if you are
using one of *them*, you might as well use iterators too.


-- 
Thomas Bellman,   Lysator Computer Club,   Linköping University,  Sweden
"When C++ is your hammer, everything         !  bellman @ lysator.liu.se
 looks like a thumb."                        !  Make Love -- Nicht Wahr!



More information about the Python-list mailing list