Home > Enterprise >  Set operations: should only work with sets, but works with dict_keys?
Set operations: should only work with sets, but works with dict_keys?

Time:04-29

The documentation for set operations says:

Note, the non-operator versions of union(), intersection(), difference(), symmetric_difference(), issubset(), and issuperset() methods will accept any iterable as an argument. In contrast, their operator based counterparts require their arguments to be sets. This precludes error-prone constructions like set('abc') & 'cbs' in favor of the more readable set('abc').intersection('cbs').

Testing this with the following experiment:

# Python 3.10.2 (main, Jan 15 2022, 19:56:27) [GCC 11.1.0] on linux

>>> set('ab') & set('ac')
{'a'}
# works, as expected

>>> set('ab') & 'ac'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for &: 'set' and 'str'
# doesn't work, as expected

>>> set('ab') & list('ac')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for &: 'set' and 'list'
# doesn't work, as expected

>>> set('ab') & iter('ac')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for &: 'set' and 'str_iterator'
# doesn't work, as expected

>>> set('ab') & dict(zip('ac', 'ac')).keys()
{'a'}
# works??

>>> type({}.keys())
<class 'dict_keys'>

>>> isinstance({}.keys(), (set, frozenset))
False

So, here is the paradox:

  • set operator & works with dict_keys objects;
  • The documentation says it should only work with sets;
  • dict_keys objects are not sets.

Why does set operator & work with dict_keys objects? Are there other types that it works with? How can I find a list of these types?

CodePudding user response:

this is not a complete answer, but dict_keys are instances of collections.abc.Set:

from collections.abc import Set
k = dict(zip('ac', 'ac')).keys()
print(isinstance(k, Set))  # -> True
  • Related