This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: dict. keys view behaviour diverges from set()
Type: behavior Stage: needs patch
Components: Interpreter Core Versions: Python 3.11
process
Status: open Resolution:
Dependencies: Superseder:
Assigned To: Nosy List: gregory.p.smith, rhettinger
Priority: normal Keywords:

Created on 2021-11-10 21:14 by gregory.p.smith, last changed 2022-04-11 14:59 by admin.

Messages (3)
msg406133 - (view) Author: Gregory P. Smith (gregory.p.smith) * (Python committer) Date: 2021-11-10 21:16
Python 3.9.7 (default, Sep 24 2021, 09:43:00) 
[GCC 10.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> dict(a=3,b=5).keys()
dict_keys(['a', 'b'])
>>> dict(a=3,b=5).keys() - 'a'
{'b'}
>>> dict(a=3,b=5).keys() - 'ab'
set()
>>> set(('a', 'b'))
{'b', 'a'}
>>> set(('a', 'b')) - 'ab'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'set' and 'str'
>>> set(('a', 'b')).difference('ab')
set()

basically it looks like the keys view treats - as .difference() whereas set() avoids bugs in its operators by requiring both to be sets.
msg406134 - (view) Author: Gregory P. Smith (gregory.p.smith) * (Python committer) Date: 2021-11-10 21:24
Joshua pointed out that https://bugs.python.org/issue26973 appears to cover this.  we rejected the idea of changing it at the time.  it'd still be nice.
msg406136 - (view) Author: Raymond Hettinger (rhettinger) * (Python committer) Date: 2021-11-10 21:43
This is a bug dictviews_sub(). It that incorrectly calls difference_update() instead of set_isub() which would perform the requisite type check.  

Note the KeysView ABC is correct and implements the type check.

This situation is unfortunate.  Adding the type check will help prevent future bugs;  however, it will likely also break some existing code that is currently working correctly.

My recommendation is to leave it as-is and live with it.  That is what we did with list.iadd() which has the same problem.
History
Date User Action Args
2022-04-11 14:59:52adminsetgithub: 89938
2021-11-10 21:43:07rhettingersetnosy: + rhettinger
messages: + msg406136
2021-11-10 21:24:16gregory.p.smithsetmessages: + msg406134
2021-11-10 21:17:27gregory.p.smithsettitle: dict. keys view behavious diverges from set() -> dict. keys view behaviour diverges from set()
2021-11-10 21:16:36gregory.p.smithsetmessages: + msg406133
2021-11-10 21:14:59gregory.p.smithcreate