python STL?

Andrew Dalke adalke at
Sat Nov 15 01:29:31 CET 2003

Ron Levine:
> [std::sort] ALREADy exists in the standard sort(lt) funciton,
> whose optional argument lt is any "less than" operator you care to
> define.

Not quite.  STL splits algorithms and containers.  Python's sort
is a method on native lists.  Suppose I make my own list-like data
structure which implements __getitem__ and __setitem__
etc. as needed for the container aspect of a list.  If I want to
sort those values I need to implement my own sort code,
with no ability to leverage the standard Python sort code.

Eg, suppose I had a fixed-width file where I can read/write
fields from the file and can replace entries, but cannot add
or delete fields.

class FileList:
  def __init__(self, filename):
    self.filename = filename
    self.infile = open(filename, "rwb")
    self._n = os.path.getsize(filename) / 40
  def __len__(self): return self._n
  def __getitem__(self, i):
    if not (0 <= i < self._n):
      raise IndexError(i)
  def __setitem__(self, i, s):
    if not (0 <= i < self._n):
      raise IndexError(i)
    assert len(s) == 40*40).write(s)

The idea is that a 'std::sort' *algorithm* should be
able to use this list-like container even though there's
no implementation similarity between it and native lists.

                    dalke at

More information about the Python-list mailing list