Reputation: 101
Why is it not possible to compare a set and ImmutableSet using the subset operator <= ? E.g. run the following code. What's the problem here? Any help appreciated. I'm using Python 2.7.
>>> from sets import ImmutableSet
>>> X = ImmutableSet([1,2,3])
>>> X <= set([1,2,3,4])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sets.py", line 291, in issubset
self._binary_sanity_check(other)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sets.py", line 328, in _binary_sanity_check
raise TypeError, "Binary operation only permitted between sets"
TypeError: Binary operation only permitted between sets
>>>
Upvotes: 2
Views: 936
Reputation: 1122222
Use a frozenset
object instead; the sets
module has been deprecated and is not comparable with the built-in types:
>>> X = frozenset([1,2,3])
>>> X <= set([1,2,3,4])
True
From the documentation for the sets
module:
Deprecated since version 2.6: The built-in
set
/frozenset
types replace this module.
If you are stuck with code using the sets
module, stick to its types exclusively when comparing:
>>> from sets import Set, ImmutableSet
>>> Set([1, 2, 3]) <= set([1, 2, 3, 4])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/mj/Development/Libraries/buildout.python/parts/opt/lib/python2.7/sets.py", line 291, in issubset
self._binary_sanity_check(other)
File "/Users/mj/Development/Libraries/buildout.python/parts/opt/lib/python2.7/sets.py", line 328, in _binary_sanity_check
raise TypeError, "Binary operation only permitted between sets"
TypeError: Binary operation only permitted between sets
>>> ImmutableSet([1, 2, 3]) <= Set([1, 2, 3, 4])
True
Python set
and frozenset
do accept any sequence for many of the operators and functions, so inverting your test also works:
>>> X
frozenset([1, 2, 3])
>>> set([1,2,3,4]) >= X
True
The same applies to the .issubset()
function on the sets.ImmutableSet
and sets.Set
classes:
>>> X.issubset(set([1,2,3,4]))
True
but not mixing the deprecated types and the new built-ins is entirely the best option.
Upvotes: 7