"a in b" calls a.__cmp__, why?

Lee Harr missive at frontiernet.net
Sat Jun 21 16:43:38 EDT 2003


In article <mailman.1056224677.5103.python-list at python.org>, Gerrit Holl wrote:
> Hello,
> 
> Why does a container-sequence's __contains__ call obj.__cmp__?
> 
>   0 >>> class Foo(object):
>   0 ...  def __cmp__(self, other):
>   0 ...   print "comparing"
>   0 ...   return cmp(id(self), id(other))
>   0 ...
>   2 >>> l=[Foo(), Foo(), Foo()]
>   3 >>> l[0] in l
> comparing
> True
> 
> Why do lists and tuples do this? Or is it unwanted/a bug?
> 

well... you might be upset if this did not work:

>>> z=[]
>>> z.append(4)
>>> 4.0 in z
1



> It means a serious impact on 
> speed for me, since I'm writing a game and __cmp__ is used to
> determine the drawing order, (layers etc.), which is not extremely
> expensive but too expensive to do each frame: I can cache my sprites
> and resort it if and only if sprites appear or disappear from a
> certain area, but I do need to do membership tests each frame...
> 
> By testing and playing, I see only one way to suppress this:
> 
>   7 >>> l[2] in dict.fromkeys(l)
> True
> 
> However, is this trick really necessary?
> 


You could create a list subclass and override __contains__ or
if this is Pygame, I would recommend using sprite.Group().has()



> P.S.
> Do other people also have CVS problems? In 98% of my tries to
> do "cvs update -PCdfR", I get an error message: either
> "reading from server: Connection reset by peer", or
> "end of file from server (consult above messages if any)". The
> same is true when diffing. In 2% of the tries, however, all
> works as it should, so I'm cvs-update'ing in a while loop
> while breaking out of it when it succeeds... :(
> 

Sourceforge? There have been many other people having problems...
Hopefully they are not all doing this, or maybe that is why the
poor sf servers can't handle it.





More information about the Python-list mailing list