469,949 Members | 2,183 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,949 developers. It's quick & easy.

sets.Set doesn't honour __eq__

I was expecting the class sets.Set to act like an
unordered list with no two members equal. But, while
the following code prints True, the assertion fails.
from sets import Set

_base = str
class caseless_string(_base):
"""Strings, but equality ignores case."""
def __eq__(self, other):
return _base.__eq__(self.upper(), other.upper())

a = caseless_string('a')
A = caseless_string('A')
print A == a

from sets import Set
assert len(Set([a,A])) == 1
If looks like Set is using dict.__setitem__. In that
case, I reckon that the following is allowed to act in
a surprising fashion. Am I correct?
from sets import Set
foo = 3
bar = 3
if len(Set([foo,bar])) == 2:
print 'Boo!'
Is there an implementation of Set around which checks
for equality, honouring __eq__ ? Any help welcome.

David Vaughan

Need a new email address that people can remember
Check out the new EudoraMail at
http://www.eudoramail.com
Jul 18 '05 #1
1 1946
David Vaughan wrote:
I was expecting the class sets.Set to act like an
unordered list with no two members equal. But, while
the following code prints True, the assertion fails.
from sets import Set

_base = str
class caseless_string(_base):
"""Strings, but equality ignores case."""
def __eq__(self, other):
return _base.__eq__(self.upper(), other.upper())
[...]


You just have to define __hash__ too:

class caseless_string(str):
"""Strings, but equality ignores case."""
def __eq__(self, other):
return str.__eq__(self.lower(), other.lower())
def __hash__(self):
return str.__hash__(self.lower())

works fine for me.

(btw, why do you do the _base trick?)

--
Ciao,
Matteo
Jul 18 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

reply views Thread by Dave Benjamin | last post: by
31 posts views Thread by John Roth | last post: by
49 posts views Thread by Steven Bethard | last post: by
3 posts views Thread by vegetax | last post: by
9 posts views Thread by Neil Benn | last post: by
2 posts views Thread by James Stroud | last post: by
14 posts views Thread by Dennis Benzinger | last post: by
5 posts views Thread by JKPeck | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.