dict.keys() does not behave as set

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
jdts
Posts: 36
Joined: Mon Dec 23, 2019 2:55 pm

dict.keys() does not behave as set

Post by jdts » Sat Jan 04, 2020 5:03 pm

I was surprised that the keys of a dict are not treated as an &'able set in µPy:

Code: Select all

>>> d={"foo":1,"bar":2,"baz":3}
>>> type(d.keys())
<class 'dict_view'>
>>> d.keys() & {'baz','foo','faz'}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported types for __and__: 'dict_view', 'set'
vs. CPython3:

Code: Select all

>>> d={"foo":1,"bar":2,"baz":3}
>>> type(d.keys())
<class 'dict_keys'>
>>> d.keys() & {'baz','foo','faz'}
{'foo', 'baz'}
Is this a known limitation of the dict_view class?

User avatar
jimmo
Posts: 2754
Joined: Tue Aug 08, 2017 1:57 am
Location: Sydney, Australia
Contact:

Re: dict.keys() does not behave as set

Post by jimmo » Sun Jan 05, 2020 5:16 am

jdts wrote:
Sat Jan 04, 2020 5:03 pm
Is this a known limitation of the dict_view class?
Yes, there's a comment in the code "// only supported for the 'keys' kind until sets and dicts are refactored" however to really be classed as a "known limitation" it should have a corresponding test in tests/cpydiff which is what's used to generated the "Differences from CPython" section of the docs.

I can see why this wasn't supported initially (it's very easy to implement but would add code size overhead), but as the comment suggests, a refactoring might make it possible to achieve this with minimal code overhead. I'll raise a bug for the cpydiff test.


jdts
Posts: 36
Joined: Mon Dec 23, 2019 2:55 pm

Re: dict.keys() does not behave as set

Post by jdts » Sun Jan 05, 2020 6:00 pm

Thanks. I checked the known diffs and didn't see anything relevant.

Damien
Site Admin
Posts: 647
Joined: Mon Dec 09, 2013 5:02 pm

Re: dict.keys() does not behave as set

Post by Damien » Mon Jan 06, 2020 12:28 pm

This difference has been added to the CPython-difference part of the docs (see github for reference).

Post Reply