How to subclass sets.Set() to change intersection() behavior?

Raymond Hettinger python at rcn.com
Tue Dec 12 23:19:43 EST 2006


[mkppk]
> I have kind of strange change I'd like to make to the sets.Set()
> intersection() method..
>
> Normally, intersection would return items in both s1 and s2 like with
> something like this:  s1.intersection(s2)
 . . .
> - the lists I am working with are small, like 1-10 items each

from sets import Set
from itertools import ifilter

class mySet(Set):
    def isDisjoint(self, other):
        if len(self) <= len(other):
            little, big = self, other
        else:
            little, big = other, self
        for elem in ifilter(big._data.has_key, little):
           return False
        return True

p = mySet('abc')
q = mySet('def')
r = mySet('cde')
print p.isDisjoint(q)
print r.isDisjoint(q)



Hope something like this works for you.


Raymond




More information about the Python-list mailing list