mirror of
https://github.com/micropython/micropython.git
synced 2025-12-16 09:50:15 +01:00
Currently, dict views (eg `dict.keys()`, `dict.values()`) do not implement
the `bool` or `len` unary operations. That may seem like a reasonable
omission for MicroPython to keep code size down, but it actually leads to
silently incorrect bool operations, because by default things are true.
Eg we currently have:
>>> bool(dict().keys())
True
which is wrong, it should be `False` because the dict is empty.
This commit implements `bool` and `len` unary operations on dict views by
simply delegating to the existing dict unary op function.
Fixes issue #12385.
Signed-off-by: Damien George <damien@micropython.org>
45 lines
831 B
Python
45 lines
831 B
Python
d = {1: 2}
|
|
for m in d.items, d.values, d.keys:
|
|
print(m())
|
|
print(list(m()))
|
|
|
|
# print a view with more than one item
|
|
print({1:1, 2:1}.values())
|
|
|
|
# `bool` and `len` unary ops
|
|
for d in ({}, {1: 2}, {1: 2, 3: 4}):
|
|
for op in (bool, len):
|
|
print(op(d.keys()), op(d.values()), op(d.items()))
|
|
|
|
# unsupported binary op on a dict values view
|
|
try:
|
|
{1:1}.values() + 1
|
|
except TypeError:
|
|
print('TypeError')
|
|
|
|
# unsupported binary op on a dict keys view
|
|
try:
|
|
{1:1}.keys() + 1
|
|
except TypeError:
|
|
print('TypeError')
|
|
|
|
# keys dict_view is not hashable
|
|
|
|
try:
|
|
hash({}.keys())
|
|
except TypeError:
|
|
print('TypeError')
|
|
|
|
# values dict_view is hashable
|
|
|
|
print(type(hash({}.values())))
|
|
|
|
# items dict_view is not hashable
|
|
|
|
try:
|
|
hash({}.items())
|
|
except TypeError:
|
|
print('TypeError')
|
|
|
|
# set operations still to come
|