diff options
| author | Damien George <damien@micropython.org> | 2025-11-19 14:41:31 +1100 |
|---|---|---|
| committer | Damien George <damien@micropython.org> | 2025-11-21 13:28:28 +1100 |
| commit | 128420359e9144369df2ed24e99217b3dc54446f (patch) | |
| tree | 5cbdf78662a9d018a1da0a14657a061d8c1c335b /tests/basics/dict_views.py | |
| parent | 45938432c6616fe684e67fdf4c5a9615a7c2fc73 (diff) | |
py/objdict: Implement bool and len unary ops for dict views.
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>
Diffstat (limited to 'tests/basics/dict_views.py')
| -rw-r--r-- | tests/basics/dict_views.py | 5 |
1 files changed, 5 insertions, 0 deletions
diff --git a/tests/basics/dict_views.py b/tests/basics/dict_views.py index a82f47b6b..45f3238f1 100644 --- a/tests/basics/dict_views.py +++ b/tests/basics/dict_views.py @@ -6,6 +6,11 @@ for m in d.items, d.values, d.keys: # 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 |
