some random reflections...

Steve Tregidgo smst at quantisci.co.uk
Thu Dec 9 11:06:50 EST 1999


Hi Alex,

Alex Martelli wrote:
> 
> 4. why can't I overload "in" to have the
>     expected semantics and maybe be fast...?
> 
> "if a in X:" and "for a in X:" will now both
> give errors unless X is a sequence.  But
> it would seem much more useful, elegant,
> natural, polymorphic, and whatever other
> buzzwords you desire, if there was some
> __whatever__ method, or methods, that
> I could overload on my object X, to make
> these operations work, without wanting to
> make X a sequence (besides, for the
> "if a in X" case, I could give my true/false
> answer much faster than the currently
> rigid linear-iteration semants of "in"...!).
> 

Try this:

class X:
  def __init__(self, length):
    self.length = length
  def __getitem__(self, item):
    if item >= self.length:    # Or whatever test you like
      raise IndexError
    import random              # Insert (useful) things here.
    return random.random()

Python 1.5.1 (#0, Aug 27 1998, 19:32:31) [MSC 32 bit (Intel)] on
win32
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>>
>>> x = X(3)
>>> for a in x:
...   print a
...
0.690979699629
0.155051548276
0.453616478203
>>> if 1 in x:
...   print 'unlikely!'
... else:
...   print 'spam'
...
spam
>>>^Z

So, if you can't easily get the Nth item but can get the "next" item
(as you mention below), you are at least okay in a for-loop -- just
remember the last thing you sent out from __getitem__ and work out
the next thing accordingly.  (I don't know how this would work for   
' if a in b ' type statements -- try it and see what happens, maybe).

> Regarding the
>     for a in X:
> case, the point is that I can well have a
> class X such that linear iteration on it is
> natural and smooth, while the random
> addressing demanded by being a sequence
> (a much stronger demand -- like being
> a random iterator, rather than an input
> iterator, in C++...) is inappropriate -- i.e.
> where I can easily get the "next" item,
> but not the "N-th item" for arbitrary N
> without a large amount of work.
> 

The locking idea is interesting, too -- not sure how you could
implement it currently, but somebody is bound to have an idea.

Cheers,
Steve Tregidgo
http://www.enviros.com/bc




More information about the Python-list mailing list